我在两个主机之间建立了全双工连接,这两个主机与一个始终监听 NetworkStream.Read() 的线程交换数据。我怎样才能优雅地关闭连接避免:
1-两侧read()函数的死锁
2- 读取线程的 abort() [安全地关闭它们]
我想关闭与 SocketShutdown.Send 的连接,但它是如何工作的?它解锁了另一边的 Read()。文档中的内容不多。
谢谢你
请您参考如下方法:
一个简单的网络交换看起来像这样:
Server: create socket
Server: listen on socket
Client: create socket
Client: connect to server's address
Server: accept connection, which returns a new socket to use for that connection
Client: receive new socket from result of connect operation
现在连接已经建立。将有一些定义的协议(protocol)用于相互通信。该协议(protocol)将决定谁开始。它可以是任何一个,但对于这个例子,我们假设它是客户端:
Client: send some data
Server: receive the data
Server: send a response
Client: receive the data
Client: shutdown with "send" (but still be prepared to receive)
Server: receive completes with 0 (indicates no more data will be sent by client)
Server: shutdown with "both"
Client: receive completes with 0 (indicates no more data will be sent by server)
Server & Client: close sockets
回答您的具体问题:
如何避免死锁?这里没有死锁的可能性。服务器和客户端通常都是使用异步网络 API 编写的。但是,如果定义的协议(protocol)是一个简单的请求/响应协议(protocol)(例如 HTTP),那么即使这样也不是严格要求的。每个端点都可以是单线程的,根据协议(protocol)在发送和接收之间交替。“你如何中止阅读线程?”你没有。如果您确实将整个线程专用于从套接字读取数据(这确实不是很好的设计),那么当线程看到一个长度为 0 字节的接收操作完成时,它就会简单地退出。
