我使用类Socket进行通信。起初我使用了Socket的Connect方法,Send和Receive方法。但后来我应该设置超时连接。根据这篇文章How to configure socket connect timeout我使用了BeginConnect,但之后我的接收让我有时间。
可以一起使用BeginnConnect,发送和接收吗?
答案 0 :(得分:1)
可以混合使用同步和异步Connect / Send / Receive方法。但是你要注意不要同时做2个电话,比如用BeginnConnect连接,然后直接尝试使用Receive。
您可以使用IAsyncResult来确定异步调用是否已完成。
此示例在同一台PC上使用tcp echo服务器时没有问题:
Socket myAsyncConnectSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
myAsyncConnectSocket.ReceiveTimeout = 10;
myAsyncConnectSocket.SendTimeout = 10;
int connectTimeout = 10;
var asyncResult = myAsyncConnectSocket.BeginConnect(
new IPEndPoint(IPAddress.Loopback, 57005), null, null);
bool timeOut = true;
if (asyncResult.AsyncWaitHandle.WaitOne(connectTimeout))
{
timeOut = false;
Console.WriteLine("Async Connected");
try
{
myAsyncConnectSocket.Send(Encoding.ASCII.GetBytes("Test 1 2 3"));
Console.WriteLine("Sent");
byte[] buffer = new byte[128];
myAsyncConnectSocket.Receive(buffer);
Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(buffer));
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.TimedOut) timeOut = true;
else throw;
}
}
Console.WriteLine("Timeout occured: {0}", timeOut);
特别关注asyncResult.AsyncWaitHandle.WaitOne()
,因为它会阻塞当前线程,直到异步连接完成为止,如果要在不同的线程上连接/发送/接收,则必须自己管理此连接状态。