Async TCP Server for multiple Clients

强颜欢笑 提交于 2019-12-05 14:30:50

See the example at http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx

You want to change your code so that it allocates a new buffer each time you call BeginReceive:

        Socket clientSocket = serverSocket.EndAccept(ar); 
        clientSocketList.Add(clientSocket);
        AppendToTextBox("ClientConnected");
        var buffer = new byte[BUFFER_LENGTH];  // <---
        clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
        serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);

You must have one buffer per client. Otherwise, one client can overwrite the buffer used by the other client.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!