我有一个多线程服务器 - 客户端系统,客户端与服务器聊天并接收发送回的消息,但只有客户端到服务器的通信方式。我想让它成为客户端到客户端。问题是我不知道如何区分客户端,并且可能将彼此的网络流连接到另一个。
我不想只为 2 个客户端制作它,而是以一种通用的方式制作它,这样我就可以连接 6 个客户端,这样每一个连接的客户端都会找到前一个连接的客户端。
我想到了一个TcpClient[]
数组,我在接受连接后存储客户端对象,但后来我就是不知道如何区分它们并将它们附加到另一个。
这是服务器类的代码:
class TheServer
{
private TcpListener tcpListener;
private Thread threadListener;
TheMessage msg;
public TcpClient[] clientList = new TcpClient[100];
private int n = 0;
public void StartServer()
{
try
{
this.tcpListener = new TcpListener(IPAddress.Any, 8000);
this.threadListener = new Thread(new ThreadStart(ListenForClients));
this.threadListener.Start();
Console.WriteLine("Local end point: " + tcpListener.LocalEndpoint);
}
catch (Exception e)
{
throw;
}
}
private void ListenForClients()
{
this.tcpListener.Start();
while(true)
{
// block until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
if (n == 0)
{
clientList[0] = client;
}
else
{
n++;
clientList[n] = client;
}
// create thread to handle communication with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(clientList[n]);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream stm = tcpClient.GetStream();
msg = new TheMessage();
while (true)
{
Byte[] bSize = new Byte[sizeof(Int32)];
stm.Read(bSize, 0, bSize.Length);
Byte[] bData = new Byte[BitConverter.ToInt32(bSize, 0)];
stm.Read(bData, 0, bData.Length);
msg = XmlRefactorServer.ByteArrayToObject<TheMessage>(bData);
String str = msg.Message;
Console.WriteLine(str);
stm.Flush();
// send back to client
msg.Message = str;
Byte[] bDataBack = XmlRefactorServer.ObjectToByteArray<TheMessage>(msg);
// NetworkStream stm2 = ------> perhaps here should get the second client stream ?!
Byte[] bSizeBack = BitConverter.GetBytes(bDataBack.Length);
stm2.Write(bSizeBack, 0, bSizeBack.Length);
stm2.Write(bDataBack, 0, bDataBack.Length);
stm2.Flush();
}
tcpClient.Close();
}