我有一个多线程服务器 - 客户端系统,客户端与服务器聊天并接收发送的消息,但只有客户端到服务器的通信方式。我想让它成为客户端到客户端。问题是我不知道如何区分客户端,也许还可以将彼此的网络流相互连接起来。
我不想仅为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();
}