SteamSocket TCP 检查设备连接

SteamSocket TCP to check for device connectivity

我正在使用 'StreamSocket' 'Tcp' 连接在 Windows IoT Core 上的主机和客户端设备之间进行通信。目前我正在使用每秒轮询来检查客户端设备的连接状态。我想知道是否有更好、更有效的方法来做到这一点。谢谢。

据我所知,没有更好的方法来做到这一点。检测StreamSocket断开有两种方法:

  • 发送心跳消息监听对方(服务器)是否关闭
  • 读取 0 长度表示流结束。

此外,您可以通过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检测网络连接。

如果您将主机更改为服务器,您的所有设备都将作为客户端连接到您的主机,您可以通过 StreamSocketListener. The event ConnectionReceived 开始侦听 tcp 端口检测连接传入和状态更改。

        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
        }
    }