首先要打开监听
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); IPEndPoint hostEntry = new IPEndPoint(getLocalmachineIPAddress(), ServerPort); Listener.Bind(hostEntry); Listener.Listen(ConnectionsQueueLength);
1. AcceptAsync异步方式
socketEventArg = new SocketAsyncEventArgs(); socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.UserToken = Listener; Listener.AcceptAsync(socketEventArg);
void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e) { if (e.LastOperation == SocketAsyncOperation.Accept) { Socket acceptSocket = e.AcceptSocket; if (acceptSocket != null) { // 处理方法 } } e.AcceptSocket = null; Listener.AcceptAsync(e); }
2. Accept方式
while (true) { Socket acceptSocket = Listener.Accept(); if (acceptSocket != null) { // 处理代码
} }
3. BeginAccept方式
while (true) { Listener.BeginAccept(new AsyncCallback(AcceptCallBack), Listener); }
private void AcceptCallBack(IAsyncResult result) { Socket acceptSocket = (Socket)result.AsyncState; // 处理方法 }