我有一个使用Socket的客户端,其下面的代码用于接收数据。

/** Some Code Above **/
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
byte[] receivedBytes = new byte[65535];
String msg = null;

public String ReceiveMessage() {
    csocket.BeginReceive(receivedBytes, 0, receivedBytes.Length, SocketFlags.None, new AsyncCallback(receiveCallback), csocket);
    receiveDone.WaitOne();
    return msg;
}

private void receiveCallback(IAsyncResult ar){
    try{
        Socket socket = (Socket)ar.AsyncState;
        socket.ReceiveTimeout = 10000;  /**** Not  Working ****/
        int received = socket.EndReceive(ar);
        byte[] dataBuf = new byte[received];
        Array.Copy(receivedBytes, dataBuf, received);
        msg = (Encoding.ASCII.GetString(dataBuf));
        Console.WriteLine("Message Received: " + msg);
        receiveDone.Set();
    }catch (SocketException e){
        if (e.SocketErrorCode == SocketError.TimedOut){
            Console.WriteLine("SocketExecption => Timeout");
        }else{
            Console.WriteLine("SocketExecption => " + e.ToString());
        }
    }catch (Exception e){
        Console.WriteLine("Execption => " + e.ToString());
    }
}

数据正在接收,但是我将ReceiveTimeout设置为10000,但是它不起作用。我是否将ReceiveTimeout放在错误的行中?如果是这样,那我应该在哪里初始化ReceiveTimeout?

我发现下面的代码在其中设置了ReceiveTimeout并且可以正常工作,但是我更喜欢使用BeginReceive()方法。
try{
    byte[] byt = new byte[65535];
    socket.ReceiveTimeout = 10000;
    socket.Receive(byt);
    Console.WriteLine("Message: " + Encoding.UTF8.GetString(byt));
}catch (SocketException e){
    if (e.SocketErrorCode == SocketError.TimedOut)
    {
        Console.WriteLine("TimeOut");
    }else{
        Console.WriteLine("Unknown SocketExecption: " + e.ToString());
    }
}catch (Exception e){
    Console.WriteLine("Unknown Exception:" + e.ToString());
}

这使我在设置ReceiveTimeout时感到困惑。

最佳答案

可能重复:
How to handle timeout in Async Socket?

ReceiveTimeout对于异步调用不起作用。建议的解决方案是使用自己的计时器。

从msdn获取Socket.ReceiveTimeout:

关于c# - 接收数据时在Socket中设置ReceiveTimeout,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39762379/

10-09 02:27