我正在开发可以从不同客户端接收一些命令的多客户端TCP/IP
服务器应用程序,并且基于这些命令,服务器将执行某些操作并相应地将响应发送回客户端。
我的问题是如何处理多个客户端,以便在处理后将相关数据发送回特定客户端。如何在向服务器发送数据时传递TCP client
的引用以及如何保留它,以便可以将响应发送回相关的TCPClient
。
我正在使用TCPlistner
来创建TCPClient
对象。那是oTCPClient = oTCPListener.AcceptTcpClient();
。因此,如何为每个NetworkStream
创建相关的TCPClient
进行沟通。
答案 0 :(得分:0)
我会创建一个ConnectedClient
类,它在构造函数中使用TCPClient
,然后在该对象中启动一个线程,该线程读取NetworkStream
的{{1}}以获取传入的数据。
您还可以在TCPClient
中使用方法来发送数据。每当您收到数据并希望回复或转发邮件时,您都可以在一个或多个存储的ConnectedClient
对象上拨打SendData
。
答案 1 :(得分:0)
以下是可以处理多个客户端并响应多个客户端的服务器示例
class MultyClientServer
{
private static int bufferSize = 2048;
private static byte[] buffer = new byte[bufferSize];
private static List<Socket> clientSockets = new List<Socket>();
private static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
Console.Title = "Server";
SetupServer();
Console.ReadKey();
CloseAllSockets();
}
private static void SetupServer()
{
Console.WriteLine("Settings Up Server Plz Wait");
serverSocket.Bind(new IPEndPoint(IPAddress.Any, YOUR PORT HERE));
serverSocket.Listen(10);
serverSocket.BeginAccept(new AsyncCallback(CallBack), null);
Console.WriteLine("Server Made");
}
private static void CallBack(IAsyncResult e)
{
try
{
Socket socket = serverSocket.EndAccept(e);
clientSockets.Add(socket);
Console.WriteLine("Client Connected");
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
serverSocket.BeginAccept(new AsyncCallback(CallBack), null);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
private static void ReceiveCallBack(IAsyncResult e)
{
try
{
Socket socket = (Socket)e.AsyncState;
int received;
try
{
received = socket.EndReceive(e);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
socket.Close();
clientSockets.Remove(socket);
return;
}
byte[] dataBuf = new byte[received];
Array.Copy(buffer, dataBuf, received);
string text = Encoding.ASCII.GetString(dataBuf);
Console.WriteLine("Client request: " + text);
string response = string.Empty;
try
{
if (command.ToLower() == "What Time is it")
{
response = DateTime.Now.ToString();
}
else if (command.ToLower() == "Whats your name")
{
response = "Tyler Gregorcyk";
}
else
{
response = "Invaled";
}
}
catch (Exception et) { Console.WriteLine(et.Message); socket.Close(); clientSockets.Remove(socket); }
if(response == string.Empty)
{
response = "Invaled";
}
if (response != string.Empty)
{
Console.WriteLine("Sent To Client: " + response);
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data);
serverSocket.BeginAccept(new AsyncCallback(CallBack), null);
}
conn.Close();
socket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, ReceiveCallBack, socket);
}
catch (Exception) { }
}
private static void CloseAllSockets()
{
foreach (Socket socket in clientSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
serverSocket.Close();
}
}
BTW这是YouTube上教程的编辑版本:https://www.youtube.com/watch?v=xgLRe7QV6QI