Socket Server to handle multiple clients request concurrently
我想使用Socket Server同时处理多个客户端的请求。
我有10个客户端,可以同时将请求发送到我的服务器。
我该如何处理?
有可能吗?
使用以下代码,我一次只能处理一个请求,完成请求后,服务器将接受下一个请求。
由于这个第十个原因,客户端需要等到9个请求完成。
任何帮助将不胜感激
以下是我用于服务器套接字的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | Socket _serverSocket; byte[] _buffer = new byte[255]; void SetupServer() { try { Console.WriteLine ("Setting up server..."); IPEndPoint ipEndPoint = new IPEndPoint (IPAddress.Parse(_ip), _port); // create server socket to listen new client's connection _serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _serverSocket.Bind (ipEndPoint); _serverSocket.Listen (100); _serverSocket.BeginAccept (new AsyncCallback (AcceptCallback), null); } catch (System.Exception ex) { Console.WriteLine ("Server failed :: {0}", ex.Message); } } void AcceptCallback(IAsyncResult ar) { Socket clientSocket = _serverSocket.EndAccept(ar); _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), clientSocket); } void RecieveCallback(IAsyncResult ar) { Socket clientSocket = (Socket)ar.AsyncState; int received = clientSocket.EndReceive(ar); // check if client is disconnected? if (received == 0) { Console.WriteLine("client is disconnected..."); return; } // do whatever you want with received data here... byte[] dataBuf = new byte[received]; Array.Copy(_buffer, dataBuf, received); string text = Encoding.ASCII.GetString(dataBuf); Console.WriteLine("Received Data: {0}", text); // accept new request clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), clientSocket); } |
您应该熟悉"多线程服务器"的概念。您应该为连接到服务器的每个客户端启动一个线程。因此,您可以同时处理多个客户端。或者,如果您想尝试更新的.NET功能,则可以使用
但是网络上有很多示例描述了如何实现这样的服务器。