假设您有以下代码。
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(HandleClientCommunication));
clientThread.Start(client);
}
private void HandleClientCommunication(object client)
{
using (TcpClient tcpClient = (TcpClient) client)
{
//Do my work
}
}
这种实现的问题在于,我在初始连接中使用的任何端口都会在客户端通信中使用,因此(尽管 tcpListener 仍在监听,它将无法接受其他连接,直到端口被释放)。
那么有没有办法告诉 tcpClient 更改它正在使用的端口,或者是通过向客户端发回新端口号并告诉它重新连接来实现此类功能的唯一方法?
IE:
TcpListener1.AcceptTcpClient(); //Wait
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientCommunication));
clientThread.Start(client);
private void HandleClientCommunication(object client)
{
using (TcpClient tcpClient = (TcpClient) client)
{
//Generate random port number send back to client and create another thread with a new tcpListener and wait again?
}
}
Looking at the code it appears that the localendpoint for the client and the remoteendpoint for the server appears to change to a different port yet the inverse in each case stays the same.
IE:
Started server tcpListener on 121
ClientLocalEndPoint: {127.0.0.1:1380}
ClientRemoteEndPoint: {127.0.0.1:121}
ServerLocalEndPoint: {127.0.0.1:121}
ServerRemoteEndPoint: {127.0.0.1:1380}
最佳答案
你这里的问题是错误的;生成一个新线程来处理 TcpClient
,然后循环回到 TcpListener.AcceptTcpClient()
不需要您更改端口;单个服务器可以在同一个套接字中获取多个连接。
否则,Web 服务器将如何同时处理多个用户?
您的代码某处出了问题。您的“每个连接线程”代码并不理想(每个连接一个线程比需要的多得多),但这是一种快速而肮脏的方式,效果很好。
你是如何构建监听器的?你和客户在做什么?后续连接究竟发生了什么?
关于c# - 动态更改 TCPClient 端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5672575/