[英]How to handle multiple active connections in a TCP C# socket server?
到目前为止,我的套接字服务器非常简单:
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
上保持标签,并将更新从其他线程发送到特定客户端?
例如,如果我有特定客户的数据,我该如何联系该客户而不是广播它? 或者,如果客户端不再连接,我该怎么办?
在此先感谢您的协助!
您用于接受多个连接的实现将创建匿名客户端,这意味着在连接超过1个之后,您将无法识别正确的客户端。 如果确定是问题所在,那么您可以做一件事,让客户端将标识符发送给服务器,例如“ Client1”。 创建一个Dictionary,然后在您的方法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);
}
}
}
请注意:您的应用程序应该足够智能,可以动态地决定将更新发送给哪个客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.