如何处理TCP c#套接字服务器中的多个活动连接
本文关键字:服务器 连接 活动 套接字 何处理 处理 TCP | 更新日期: 2023-09-27 18:08:25
目前为止,我的套接字服务器非常简单:
public static void listen()
{
TcpListener server = null;
IPAddress address = IPAddress.Parse("127.0.0.1");
try
{
server = TcpListener.Create(5683);
server.Start();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
while (true)
{
Thread.Sleep(10);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Accepted Client");
Thread thread = new Thread (new ParameterizedThreadStart(SwordsServer.ClientHandler));
thread.IsBackground = true;
thread.Start(client);
}
}
public static void ClientHandler(object c)
{
TcpClient client = (TcpClient)c;
NetworkStream netstream = client.GetStream();
bool connected = true;
while (connected)
{
Thread.Sleep(10);
try
{
byte[] bytes = new byte[client.ReceiveBufferSize];
netstream.Read(bytes, 0, bytes.Length);
Console.WriteLine("got data");
netstream.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
connected = false;
Console.WriteLine(e);
Console.WriteLine(e.StackTrace);
}
}
}
我的问题是,在概念层面上,你如何在每个唯一的client
上保持标签,并从其他线程发送更新到特定的客户端?
例如,如果我有一个特定客户端的数据,我如何到达该客户端而不是广播它?或者,如果客户端不再连接,我怎么知道?
提前感谢您的帮助!
接受多个连接的实现创建了匿名客户端,这意味着在超过一个连接后,您将无法识别正确的客户端。如果识别是问题,那么您可以做一件事,让客户端向服务器发送标识符,如"Client1"。创建一个字典,并在方法ClientHandler()中从客户端读取标识符,并将TCPClient的对象添加到字典中。
那么修改后的代码应该是这样的:
Dictionary<string, TCPClient> dictionary = new Dictionary<string, TCPClient>();
public static void ClientHandler(object c)
{
TcpClient client = (TcpClient)c;
NetworkStream netstream = client.GetStream();
bool connected = true;
while (connected)
{
Thread.Sleep(10);
try
{
byte[] bytes = new byte[client.ReceiveBufferSize];
//read the identifier from client
netstream.Read(bytes, 0, bytes.Length);
String id = System.Text.Encoding.UTF8.GetString(bytes);
//add the entry in the dictionary
dictionary.Add(id, client);
Console.WriteLine("got data");
netstream.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
connected = false;
Console.WriteLine(e);
Console.WriteLine(e.StackTrace);
}
}
}
注意:你的应用程序应该足够智能,可以动态地决定应该向哪个客户端发送更新