在socket网络编程过程中,连接、发送数据、接收数据都要用到ManualResetEvent 来协调异步通信进程。
连接
sock.BeginConnect(MyServer,
new AsyncCallback(ConnectCallback), sock)
connectDone.WaitOne();
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
sock.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), sock);
sendDone.WaitOne();
......
sock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
connectDone.Set();//此后,主线程才执行connectDone.WaitOne()后面的内容
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
connectDone.Set();
}
}
发送
sock.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), sock);
sendDone.WaitOne();
private void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
sendDone.Set();//此后,主线程才执行connectDone.WaitOne()后面的内容
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}