C#中Socket的Accept()和BeginAccept()的区别
区别在于:Accept()是同步的,BeginAccept()是异步的
调用accept()或者BeginAccept()函数来接受客户端的连接,这就可以和客户端通信了。
BeginAccept()会开启一个异步操作来获取连接的Socket,而Accept()会将程序在该位置中断来等待连接。
使用 BeginAccpet() 在启动程序后,程序会跳过代码,直接运行结束,而使用 Accept() 时程序则会在当前位置停止
实例:
Utils.socketAccept = new AsyncCallback(SocketConnected.ClientAccepted);
Utils.iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
if (Utils.mySocket == null)
{Utils.mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);Utils.mySocket.Bind(Utils.iep);Utils.mySocket.Listen(10);
}
Utils.mySocket.BeginAccept(Utils.socketAccept, Utils.mySocket);
mySocket.BeginAccept(MachineMaster.socketAccept, MachineMaster.mySocket);
public IAsyncResult BeginAccept(AsyncCallback callback, object state);
public static AsyncCallback socketAccept;
socketAccept = new AsyncCallback(SocketConnected.ClientAccepted);
public class SocketConnected
{public static void ClientAccepted(IAsyncResult ar){try{Utils.connectedCount++;var socket = ar.AsyncState as Socket;var client = socket.EndAccept(ar);IPEndPoint clientipe = (IPEndPoint)client.RemoteEndPoint;Utils.tsk.UpdateLog(clientipe + " is connected,total connects " + Utils.connectedCount);client.BeginReceive(Utils.buffer, 0, Utils..buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);}catch (Exception ex){Utils.tsk.UpdateLog(ex.Message);}}}