gpt4 book ai didi

c# - Socket接收数据时设置ReceiveTimeout

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:03 25 4
gpt4 key购买 nike

我有一个使用 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 不适用于异步调用。建议的解决方案是使用自己的计时器。

来自 Socket.ReceiveTimeout 的 msdn :

This option applies to synchronous Receive calls only. If the time-out period is exceeded, the Receive method will throw a SocketException.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com