我的socket服務器是相當簡單的,到目前爲止:如何處理TCP C#套接字服務器中的多個活動連接?
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
選項卡,並從其他線程更新發送到特定的客戶端?
例如,如果我有特定客戶端的數據,我如何接觸客戶端而不是廣播它?或者,如果客戶不再連接,我怎麼知道?
在此先感謝您的幫助!
添加列表對象列表客戶端。 –
jdweng
但是,我該如何引用該列表中的特定TCPClient?我將如何區分他們? – MrDysprosium
一種方法是使用客戶端的IP地址。或者給每個客戶一個ID。 – jdweng