可以说你有以下代码。动态更改TCPClient端口
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?
}
}
看代码似乎 客户端的localendpoint和 的remoteendpoint服务器 似乎更改为不同的端口 但在每种情况下,逆停留在 相同。
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}
检查“接受者”和“事件循环”模式 – bobah 2011-04-15 07:13:01