kerryjiang / SuperSocket

SuperSocket is a light weight, cross platform and extensible socket server application framework.
Apache License 2.0
3.94k stars 1.14k forks source link

Command queue and keep alive commands #608

Open panterlo opened 2 years ago

panterlo commented 2 years ago

I am trying to construct a TCP Socket Server and TCP Clients that ensures they always try to reconnect on any kind of disconnect e.g persistent connection. I am using the StringPackageInfo with the CommandLinePipeFilter and sending keep alive commands that needs to be acknowledged by the server at periodic intervals. The code is briefly explained below. Would this be the best way to handle this scenario ? The second question is if there is an example / sample code explaning what's the best way to handle Command with a response scenario. I would think a queue is needed to gurantee each command is written and read from the socket otherwise command responses will get mixed up quickly. Any idea of a simple solution ?

Essentially this code:

   try
            {
                if (connected == true)
                {
                    Console.WriteLine("Sending keep alive message");
                    await _client.SendAsync(Encoding.UTF8.GetBytes("ALIVE\r\n"));
                    Console.WriteLine("Waiting for alive response");
                    var response = await _client.ReceiveAsync();
                    Console.WriteLine($"Got alive response {response?.Key}");

                    if (response == null || response.Key != "OK")
                       Connect();
                }
                else
                {
                    Console.WriteLine($"Trying to connect");
                    connected = await _client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 4060), token);

                    if (connected == true)
                    {
                        _client.Closed += _client_Closed; // This is set to null when the socket closes
                        Console.WriteLine($"Connected: {connected}");
                    }
                    else throw new Exception("Not connected");
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }