private void PreventErrorListen()
{
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
LocalIP = new IPEndPoint(LocalIPAddress, int.Parse(textBox_Listen_Port.Text));
Listener.Bind(LocalIP);
listBox_Receive_Status.Items.Add("开始监听端口" + textBox_Listen_Port.Text + "...");
Listener.Listen(1);
MessageBox.Show("PreventErrorListen Listener.Connected="+Listener.Connected);
Listener.BeginAccept(new AsyncCallback(OnConnectRequest), Listener);
ListenDone.WaitOne();
}
public void OnConnectRequest(IAsyncResult ar)
{
listBox_Receive_Status.Items.Add("进入OnConnectRequest");
// Signal the main thread to continue.
ListenDone.Set();
MessageBox.Show("OnConnectRequest Listener.Connected=" + Listener.Connected);
Socket Listener1 = (Socket)ar.AsyncState; //此处的Listener是局部变量
MessageBox.Show("OnConnectRequest Listener1.Connected=" + Listener1.Connected);
try
{
ClientEndAccept = Listener1.EndAccept(ar);
listBox_Receive_Status.Items.Add("成功接受客户机" + ClientEndAccept.RemoteEndPoint + "的连接请求。。。");
//刚刚建立客户机与主机之间的连接
ClientEndAccept.BeginReceive(Receive_Buffer, 0, Receive_Buffer.Length, SocketFlags.None, new AsyncCallback(OnReceiveData), ClientEndAccept);
ReceiveDone.WaitOne();
Listener.BeginAccept(new AsyncCallback(OnConnectRequest), Listener);
ListenDone.WaitOne();
}
catch { }
}
这里是我的监听部分阿