SteamSocket TCP检查设备连接

时间:2018-10-17 05:05:24

标签: c# tcp uwp windowsiot

我正在使用“ StreamSocket”“ Tcp”连接在Windows IoT核心版上的主机和客户端设备之间进行通信。目前,我每秒使用一次轮询来检查客户端设备的连接状态。我想知道是否有更好,更有效的方法。谢谢。

1 个答案:

答案 0 :(得分:1)

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

  • 发送心跳消息以监视另一端(服务器)是否关闭。
  • 读取0长度表示流的结尾。

此外,您可以通过NetworkInformation.NetworkStatusChanged来检测网络连接。这样,应用程序就可以知道网络是否无效,这是导致StreamSocket断开连接的主要原因。有关更多信息,请参见Reacting to network status changes

如果将主机更改为服务器,将所有设备更改为连接到主机的客户端,则可以通过 StreamSocketListener 开始监听TCP端口。事件 ConnectionReceived 可以检测到连接传入和状态更改。

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