我想使用Socket Server同时处理多个客户端的请求。 我有10个客户端,可以同时向我的服务器发送请求。 我怎么能处理这个? 有可能吗?
使用以下代码,我一次只能处理一个请求,在请求完成后,服务器接受下一个请求。 由于第10个客户需要等到9个请求完成。
任何帮助将不胜感激
以下是我用于Server Socket的代码
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);
}
答案 0 :(得分:1)
您应该熟悉“多线程服务器”的概念。您应该为连接到服务器的每个客户端启动一个线程。因此,您可以同时处理多个客户端。或者,如果要尝试较新的.NET功能,可以使用Tasks Parallel Library
。
但是网上有很多例子描述了如何实现这样的服务器。