我有一个服务器,允许我连接多个客户端从客户端接收消息,并在连接时向每个客户端发送消息。 我要做的是从客户端向另一个发送消息,因此所有服务器应该做的是从第一个客户端获取消息并发送给另一个客户端。我怎么能这样做?
这是服务器的代码
class Server
{
private TcpListener tcpListener; private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Console.WriteLine(ex.Message);
}
if (bytesRead == 0)
{
//the client has disconnected from the server
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
tcpClient.Close();
}
static void Main(string[] args)
{
new Server();
}
}
和客户
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
//message has successfully been received
byte[] message = new byte[4096];
int bytesRead;
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
Console.ReadLine();
}
答案 0 :(得分:1)
您必须将传入的TcpClient
对象保留在内存中,以便以后可以发送给它们。
类似的东西:
List<TcpClient> connectedClients = new List<TcpClient>();
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
connectedClients.Add(client);
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
然后您可以正常地将客户端从列表中取出(或者只是发送到整个列表)。您可能希望将TcpClient
封装到一个成熟的“客户端”对象中,以便您可以跟踪它们发送/接收的内容并向特定客户端发送消息。