doghappy / socket.io-client-csharp

socket.io-client implemention for .NET
MIT License
721 stars 124 forks source link

Socket quickly disconnects after establishing Connection. #287

Closed sarangsurve closed 2 years ago

sarangsurve commented 2 years ago

Using TargetFramework = netcoreapp3.1, I am trying to connect to SocketIO Server which has EIO 4. Due to some infra issue, we are establishing the connection to the server using Websocket TransportProtocol. We do have auth check at the server end. So We have also used Auth options to pass the dictionary value. As much as we can see through logs on the server end, It is connecting the server and receiving auth value as expected and the socket gets authenticated. But after connecting, it gets disconnected within a few seconds. Already checked the Server log, and it is receiving a “transport close” message for the client’s pingTimeout.

Below is the code snippet that I am trying to perform at the C# client end:

using System;
using SocketIOClient;

namespace DotNetCoreWebSocket
{
    internal class Program
    {
        static void Main(string[] args)
        {
            WebSocketDemo wsObject = new WebSocketDemo(username: "user", password: "pass", publicKey: "ABCDEFGHIKLMNOPQRSTUVWXYZ");
            wsObject.Connect();
            Console.WriteLine("Is WS Connected? " + wsObject.isConnected());
            wsObject.watch(new string[] { "ipl~mivsrcb~02052022", "ucl~fcbvsmcu~02052022" });
            wsObject.ticker((data) =>
            {
                Console.WriteLine("Ticker Data:");
                Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(data));
            });
        }
    }

    public class WebSocketDemo
    {
        private string _username;
        private string _password;
        private string _publicKey;
        private Uri _hostname = new Uri("ws://localhost/");
        private SocketIO _socket = new SocketIO(new Uri("ws://localhost/"));

        public WebSocketDemo(string username, string password, string publicKey, string hostname = "ws://localhost/")
        {
            _username = username;
            _password = password;
            _hostname = new Uri(hostname);
            _publicKey = publicKey;
        }

        public bool isConnected() { return _socket.Connected; }

        public static void Socket_OnReconnecting(object sender, int e) { }

        public void Connect()
        {
            if (_socket.Disconnected)
            {
                var _socket = new SocketIO(_hostname, new SocketIOOptions
                {
                    EIO = 4,
                    Auth = new System.Collections.Generic.Dictionary<string, string>
                    {
                        { "username", _username },
                        { "password", _password },
                        { "publicKey", _publicKey }
                    },
                    ConnectionTimeout = TimeSpan.FromSeconds(10),
                    Reconnection = true,
                    ReconnectionAttempts = 5,
                    Transport = SocketIOClient.Transport.TransportProtocol.WebSocket,
                    ExtraHeaders = new System.Collections.Generic.Dictionary<string, string>
                    {
                        { "User-Agent", "dotnet-socketio[client]/socket" }
                    },
                });
                _socket.ConnectAsync();
                Console.ReadLine();
                if (_socket.Disconnected)
                {
                    int count = 0;
                    while (_socket.Disconnected)
                    {
                        count += 1;
                        _socket.OnReconnectAttempt += Socket_OnReconnecting;
                    }
                    Console.WriteLine($"{DateTime.Now} Reconnected after {count} attempt.");
                }
                if (_socket.Connected) { Console.WriteLine("Socket-Id: " + _socket.Id); }
            }
        }

        public void reconnect()
        {
            int count = 0;
            while (_socket.Disconnected)
            {
                count += 1;
                _socket.OnReconnectAttempt += Socket_OnReconnecting;
            }
            Console.WriteLine($"{DateTime.Now} Reconnected after {count} attempt.");
        }

        public void watch(string[] sportsEventList)
        {
            if (_socket.Disconnected)
                reconnect();
            if (_socket.Connected) { Console.WriteLine("Socket-Id: " + _socket.Id); }
            foreach (string sportsEvent in sportsEventList)
            {
                _socket.EmitAsync("join", sportsEvent);
                Console.WriteLine("Socket subscribed:" + sportsEvent);
            }
        }

        public async void unWatch(string[] sportsEventList)
        {
            foreach (string sportsEvent in sportsEventList)
            {
                await _socket.EmitAsync("leave", sportsEvent);
                Console.WriteLine("Socket unsubscribed:" + sportsEvent);
            }
        }

        public async void ticker(Action<Object> callback)
        {
            if (_socket.Connected) { Console.WriteLine("Socket-Id: " + _socket.Id); }

            _socket.On("footballEvent", response =>
            {
                callback(response.GetValue());
            });
            _socket.On("cricketEvent", response =>
            {
                callback(response.GetValue());
            });

            if (_socket.Disconnected)
                await _socket.ConnectAsync();
            Console.ReadLine();
        }

    }

}

I need help to resolve this issue.

sarangsurve commented 2 years ago

I tried many ways to establish a socket connection and keep it alive. Right now, I finally found a proper solution that works as per my expected result.

using System;
using System.Threading.Tasks;
using SocketIOClient;
namespace DotNetCoreWebSocket
{

    internal class Program
    {
        static async Task Main(string[] args)
        {
            WebSocketDemo wsObject = new WebSocketDemo(username: "user", password: "pass", publicKey: "ABCDEFGHIKLMNOPQRSTUVWXYZ");
            await wsObject.Connect();
            Console.WriteLine("Is WS Connected? " + wsObject.isConnected());
            await wsObject.watch(new string[] { "ipl~mivsrcb~02052022", "ucl~fcbvsmcu~02052022" });
            wsObject.ticker((data) =>
            {
                Console.WriteLine("Ticker Data:");
                Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(data));
            });
        }
    }

    public class WebSocketDemo
    {
        private string _username;
        private string _password;
        private string _publicKey;
        private Uri _hostname = new Uri("ws://localhost/");
        private SocketIO _socket = new SocketIO(new Uri("ws://localhost/"));
        public WebSocketDemo(string username, string password, string publicKey, string hostname = "ws://localhost/")
        {
            _username = username;
            _password = password;
            _hostname = new Uri(hostname);
            _publicKey = publicKey;
        }
        public bool isConnected() { return _socket.Connected; }
        public static void Socket_OnReconnecting(object sender, int e) { }
        public async Task Connect()
        {
            if (_socket.Disconnected)
            {
                var _socket = new SocketIO(_hostname, new SocketIOOptions
                {
                    EIO = 4,
                    Auth = new System.Collections.Generic.Dictionary<string, string>
                    {
                        { "username", _username },
                        { "password", _password },
                        { "appKey", _publicKey }
                    },
                    ConnectionTimeout = TimeSpan.FromSeconds(10),
                    Reconnection = true,
                    ReconnectionAttempts = 5,
                    Transport = SocketIOClient.Transport.TransportProtocol.WebSocket,
                    ExtraHeaders = new System.Collections.Generic.Dictionary<string, string>
                    {
                        { "User-Agent", "dotnet-socketio[client]/socket" }
                    },
                });
                await _socket.ConnectAsync();
                if (_socket.Disconnected)
                {
                    int count = 0;
                    while (_socket.Disconnected)
                    {
                        count += 1;
                        _socket.OnReconnectAttempt += Socket_OnReconnecting;
                    }
                    Console.WriteLine($"{DateTime.Now} Reconnected after {count} attempt.");
                }
                if (_socket.Connected) { Console.WriteLine("Socket-Id: " + _socket.Id); }
            }
        }
        public async Task watch(string[] sportsEventList)
        {
            foreach (string sportsEvent in sportsEventList)
            {
                await _socket.EmitAsync("join", sportsEvent);
                Console.WriteLine("Socket subscribed:" + sportsEvent);
            }
        }
        public async Task unWatch(string[] sportsEventList)
        {
            foreach (string sportsEvent in sportsEventList)
            {
                await _socket.EmitAsync("leave", sportsEvent);
                Console.WriteLine("Socket unsubscribed:" + sportsEvent);
            }
        }
        public void ticker(Action<Object> callback)
        {
            while (_socket.Connected)
            {
                _socket.On("footballEvent", response =>
                {
                    callback(response.GetValue());
                });
                _socket.On("cricketEvent", response =>
                {
                    callback(response.GetValue());
                });
            }
        }
    }
}

Sorry @doghappy for opening this issue.