0

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.

kara
  • 3,205
  • 4
  • 20
  • 34
Bhushan Gholave
  • 157
  • 2
  • 9
  • I have the same problem.. did you solve your problem? thanx – ertan2002 Jul 14 '19 at 21:58
  • @ertan2002 unfortunately no... There is no implementation available for socket on .net side. or half is available I can say. I will create github repo and implement it. – Bhushan Gholave Jul 16 '19 at 05:49
  • I've solved the problem by using SocketIoClientDotNet. Just be aware that you should give direct url without any extension such as EIO or transport etc. for example: localhost:1453 and it works for desktop and xamarin.mobile and my framework was 4.5 – ertan2002 Jul 16 '19 at 07:32

1 Answers1

1

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

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
ertan2002
  • 1,458
  • 1
  • 32
  • 68
  • .Net version 4.5 I can do that as well I need backword compatible with .net 2.0 and using webhttprequest? also are you following socket.io protocols like long polling first using http then websocket and then creating room and communicate? – Bhushan Gholave Jul 17 '19 at 07:07
  • @BhushanGholave I would like to have also .net standard (not sure you are talking about .net 2.0 framework or standard) but .net standard has not been supported.. and why u will use webhttprequest? Read engine.io (goal topic) and you will see that they made what u said.. – ertan2002 Jul 17 '19 at 07:30