如何判断UWP套接字何时断开?

时间:2015-11-25 06:47:12

标签: c# sockets uwp

所以我有这个程序使用通用Windows平台的套接字。我已设置从客户端接收此字节以关闭和打开此灯。这是大量的套接字代码。

    private static void AccepCallback(object sender, SocketAsyncEventArgs e)
    {
        // When connection is found start receiving data for the lifetime of the program
        while (e.AcceptSocket.Connected)
        {
            // Create some socket event args
            SocketAsyncEventArgs eReceive = new SocketAsyncEventArgs();

            // Create the buffer of data to be read in (with nothing in it)
            byte[] buffer = new byte[1];

            // Set the buffer to the event arguments
            eReceive.SetBuffer(buffer, 0, buffer.Length);

            // Subscribe the event to the function Receive
            eReceive.Completed += Receive;
            if (!e.AcceptSocket.ReceiveAsync(eReceive))
                Receive(e.AcceptSocket, eReceive);
        }
    }

它有效,但我有一个问题。退出客户端时,e.AcceptSocket.Connected保持为true,并且永远停留在该循环中。我希望它退出该循环并继续在另一个循环中监听连接。是否有函数调用我需要更新e.AccepSocket.Connected的标志?或者是否有一个完全不同的标志我应该用来判断客户端是否连接到服务器。

2 个答案:

答案 0 :(得分:0)

使用像这样的东西

while (e.AcceptSocket.Connected && e.AcceptSocket.Available > 0)
{
     // Create some socket event args
     SocketAsyncEventArgs eReceive = new SocketAsyncEventArgs();

     // Create the buffer of data to be read in (with nothing in it)
     byte[] buffer = new byte[e.AcceptSocket.Available];
     .
     .
     .

答案 1 :(得分:0)

您需要向套接字发送一个0字节并检查套接字是否正在返回成功将阻止

试试这个:

byte[] arr = new byte[1];
SocketError se = SocketError.SocketError;
e.AcceptSocket.Send(arr, 0, 0, SocketFlags.None, out se);
bool bConnected =  ((se == SocketError.Success) || (se == SocketError.WouldBlock));