我有一个客户端使用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时感到困惑。
答案 0 :(得分:1)
可能重复: How to handle timeout in Async Socket?
ReceiveTimeout不适用于异步调用。建议的解决方案是使用自己的计时器。
来自msdn的Socket.ReceiveTimeout:
此选项仅适用于同步接收呼叫。如果超出超时时间,Receive方法将抛出SocketException。