我需要监听套接字异步,但是我也希望能够通过同一个套接字发回数据但是我会被连续停留在while循环中。如何继续监听但能够通过套接字发回数据?这是我对异步连接和监听的代码。
sock1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result;
result = sock1.BeginConnect(Host1, Comm.PortInt, null, null);
bool success = result.AsyncWaitHandle.WaitOne(1000, true);
if (!success)
{
sock1.Close();
throw new Exception("Could not connect to " + Host);//baseDissConnects
}
sock1.SendTimeout = 1000;
sock1.ReceiveTimeout = 1000;
//sock1.Connect(Host1, Comm.PortInt);
sock1.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 512 * 1024);
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) //cool way to exit
{
if (IsConnected(sock1))
{
if (sock1.Available > 0)
{
ProcessResponse(sock1);
}
}
}
任何帮助都会受到赞赏,因为我不确定是否需要通过多线程来实现这一点。