gpt4 book ai didi

.net - TCPListener blues,无法弄清楚为什么连接没有正确关闭

转载 作者:行者123 更新时间:2023-12-03 11:57:26 25 4
gpt4 key购买 nike

我的 TCPListener 配置如下:

this.tcpListener = new TcpListener(IPAddress.Any, config.portNum);

然后我(使用线程)设置一个监听器函数,如下所示:
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

ThreadStart starter = delegate { HandleClientComm(client, this.DBGrid); };
Thread thread = new Thread(starter);
thread.Start();
}
}

第一次使用它,第二次触发它,我收到以下错误消息:

每个套接字地址(协议(protocol)/网络地址/端口)通常只使用一次
允许

在线程内部有一个关闭的调用:
tcpClient.Close();

但它似乎并没有释放端口,有什么建议吗?

最佳答案

如果您调用 ListenForClients反复,这是您问题的根源,而不是客户端连接不 Close()正确。
传统上,一个线程将处理打开主套接字并接受“子”连接套接字。所以你的ListenForClients应该在主服务器线程中,并且每个应用程序只调用一次。
更多信息:

this.tcpListener.Start(); 
在您指定的端口创建一个监听。随着每个客户的连接,
TcpClient client = this.tcpListener.AcceptTcpClient();
line 将创建一个新的套接字,该套接字已连接并且位于完全不同的端口上。因此,通过关闭您的客户端,您根本不会释放您的主套接字。
来自 http://en.wikipedia.org/wiki/Internet_socket#Socket_states_and_the_client-server_model

Computer processes that provide application services are called servers, and create sockets on start up that are in listening state. These sockets are waiting for initiatives from client programs. For a listening TCP socket, the remote address presented by netstat may be denoted 0.0.0.0 and the remote port number 0.

A TCP server may serve several clients concurrently, by creating a child process for each client and establishing a TCP connection between the child process and the client. Unique dedicated sockets are created for each connection. These are in established state, when a socket-to-socket virtual connection or virtual circuit (VC), also known as a TCP session, is established with the remote socket, providing a duplex byte stream.

关于.net - TCPListener blues,无法弄清楚为什么连接没有正确关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7662311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com