How to call Server Events (nodejs socket.io) from C# WebSocket4net

3k Views Asked by At

I am setting up C# websocket client for server implemented in nodejs(using socket.io). Using [Websocket4net]:https://github.com/kerryjiang/WebSocket4Net. My code is able to connect with socket server but WebClient.Send("message") does not invoke server events. I am stuck at sending message or calling events from server using websocket4net lib. I chose this library because my implementation is in framework 2.0 or less.

I have tried using websocket.send("message") to invoke message event after connection but it is not recognized at server. Failed to call function at server. Also looked into Execute Command but not able to implement this in my class.

public class JniorWebSocket : IDisposable
{
    //public delegate void LogEventHandler(object sender, LogEventArgs args);
    //public event LogEventHandler Log;
    public event EventHandler Connected;
    public event EventHandler Disconnected;

    private WebSocket _websocket;
    private string _uri;
    private string sid;

    public JniorWebSocket(string host) : this(host, 0) { }

    public JniorWebSocket(string host, int port)
    {
        _uri = "ws://" + host;
        if (0 != port) _uri += ":" + port + "/join/?EIO=3&transport=websocket";

        _websocket = new WebSocket(_uri);
        _websocket.Opened += new EventHandler(websocket_Opened);
        _websocket.Error += Websocket_Error;
        _websocket.Closed += websocket_Closed;
        _websocket.MessageReceived += Websocket_MessageReceived;

        _websocket.Open();
    }

    public void Dispose()
    {
        _websocket.Dispose();
        GC.SuppressFinalize(this);
    }
    public bool AllowUnstrustedCertificate
    {
        get
        {
            return _websocket.AllowUnstrustedCertificate;
        }
        set
        {
            _websocket.AllowUnstrustedCertificate = value;
        }
    }

    public void Connect()
    {
        _websocket.Open();
        while (_websocket.State == WebSocketState.Connecting) { };
        if (_websocket.State != WebSocketState.Open)
        {
            throw new Exception("Connection is not opened.");
        }
    }

    public void Close()
    {
        _websocket.Close();
    }

    public void Send(string message)
    {
        try
        {
            _websocket.Send(message);
        }
        catch (Exception ex)
        {
        }
    }
    private void Websocket_Error(object sender, ErrorEventArgs e)
    {
    }

    private void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
    {
        if (e.Message.IndexOf("{") != -1)
        {
            var json = JObject.Parse(e.Message.Substring(e.Message.IndexOf("{")));

            sid = json["sid"].ToString();

            Console.WriteLine(sid);
            if ("Error".Equals(sid)) HandleErrorMessage(json);
        }
    }
    private void HandleErrorMessage(JObject json)
    {
    }
    private void websocket_Opened(object sender, EventArgs e)
    {
        Connected?.Invoke(this, EventArgs.Empty);
        Send(string.Empty);
    }

    private void websocket_Closed(object sender, EventArgs e)
    {
        Disconnected?.Invoke(this, EventArgs.Empty);
    }
}

Calling this class from my main

JniorWebSocket jniorWebSocket = new JniorWebSocket(uri, port);
jniorWebSocket.AllowUnstrustedCertificate = true;
jniorWebSocket.Connect();
jniorWebSocket.Send("message");

socket.io on nodejs side

const server = require('http').Server(app);
global.socketIO = SocketIO(server, { path: '/join' });
global.socketIO.on('connection', (socket) => 
{
    socket.on('message',async (data) => {
        console.info(data);
    });
    socket.on('authenticate', async (data) => {
        try {
             }
        } catch(error) {
            console.warn('Error while authenticating socket', error);
        }
    });
});

I am new to this websocket C# implementation and not getting how I can invoke server events and after that i will write some events on client side as well. Expect to invoke all server events from client.

1

There are 1 best solutions below

2
ertan2002 On

It works for a desktop app and a xamarin.android app

I've used this library even it is deprecated https://github.com/Quobject/SocketIoClientDotNet

u can install directly from nuget Install-Package SocketIoClientDotNet

using Quobject.EngineIoClientDotNet.Client.Transports;
using Quobject.SocketIoClientDotNet.Client;



     var option = new IO.Options()
                {
                  QueryString = "Type=Desktop",
                  Timeout = 5000,
                  ReconnectionDelay = 5000,
                  Reconnection = false,                   
                  ransports = Quobject.Collections.Immutable.ImmutableList.Create<string>(PollingXHR.NAME)
                };

                socket = IO.Socket("http://localhost:1453",option);
                socket.On(Socket.EVENT_CONNECT, () =>
                {
                    socket.Emit("iAmOnline", "1234");

                });
                socket.On("youAreOnline", () =>
                {
                    Console.WriteLine("I am Online");
                });

                socket.On("hi", (data) =>
                {
                    Console.WriteLine(data);
                    socket.Disconnect();
                });

you can add any transport as you wish. I've added xhr-polling because of the firewall. You can use WebSocket.NAME and/or Polling.NAME