Search code examples
c#tcpuwpwindowsiot

SteamSocket TCP to check for device connectivity


I am using 'StreamSocket' 'Tcp' connection to communicate between my host and client devices on Windows IoT Core. Currently I am using polling every second to check for connectivity status of client devices. I would like to know if there is any better and efficient way of doing it. Thanks.


Solution

  • As I know there is no better way to do that. There are two ways of detect StreamSocket disconnect:

    • send heartbeat message to monitor if the other side(server) is closed.
    • read 0-length means end of the stream.

    In addition, you can detect the network connection via NetworkInformation.NetworkStatusChanged.By this, the app is able to know if the network is invalid, as the main reason causes the StreamSocket disconnected. More information please see Reacting to network status changes.

    If you change the host as server, all of your device as a client which connected to your host, you can start listening a tcp port via StreamSocketListener. The event ConnectionReceived could detect the connection incoming and status changed.

            StreamSocketListener listener = new StreamSocketListener();
            listener.ConnectionReceived += OnConnection;
    
    
        private async void OnConnection(
            StreamSocketListener sender, 
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        //Detect disconnection
                        return;
                    }
    
                    // Read the string.
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data. 
                        //Detect disconnection
                        return;
                    }
    
                    //TO DO SOMETHING
                }
            }
            catch (Exception exception)
            {
                 //TO DO SOMETHING
            }
        }