c# - 动态更改 TCPClient 端口

标签 c# multithreading sockets tcp

假设您有以下代码。

 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/

相关文章:

c# - StackPanel 的一侧有一个按钮,另一侧有其他按钮

C# 从具有约束的泛型推断类型

python - 未在 supervisord 下执行的线程

python - 避免重复结果 多线程 Python

c - 套接字 : listen with backlog and accept

c# - PowerBI Embedded - GetTables 导致未经授权

c# - 打开一个包含来自 gridview 单元格的详细信息的 ajax modalpopup

c++ - STL vector 多线程

c - 多进程如何绑定(bind)到一个udp端口

Node.js TCP 套接字在轮询前等待几秒钟? (net.createServer)