简体   繁体   English

全双工Tcp数据交换C#

[英]full duplex Tcp data exchange c#

I have a full duplex connection between two hosts that exchange datas with a thread that always listen on NetworkStream.Read(). 我在两个主机之间使用全双工连接,这些主机与始终在NetworkStream.Read()上侦听的线程交换数据。 How can I close gracefully the connection avoiding: 我如何优雅地关闭连接,避免:

1- the deadlock of the two side read() function 1-两侧read()函数的死锁

2- the abort() of reading threads [closing they safely] 2-读取线程的abort()[安全关闭它们]

I think closing the connection with SocketShutdown.Send but how it works? 我想用SocketShutdown.Send关闭连接,但是它如何工作? It unlock the Read() on the other side.. There are not many things in the documentation. 它将另一端的Read()解锁。文档中没有很多东西。

Thak you 解冻你

A simple network exchange looks something like this: 一个简单的网络交换如下所示:

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

Now the connection is established. 现在建立连接。 There will be some defined protocol for communicating with each other. 将会有一些已定义的协议用于彼此通信。 That protocol will dictate who starts. 该协议将决定谁开始。 It can be either, but for this example, let's assuming it's the client: 可以是任何一个,但在此示例中,我们假设它是客户端:

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

Answering your specific questions: 回答您的特定问题:

  1. How is deadlock avoided? There's no deadlock potential here. 这里没有死锁的可能性。 Servers and clients both are often written using asynchronous networking APIs. 服务器和客户端通常都是使用异步网络API编写的。 But if the defined protocol is a straightforward request/response protocol (eg HTTP), even that's not strictly required. 但是,如果定义的协议是直接的请求/响应协议(例如HTTP),则即使不是严格要求也是如此。 Each end can be single-threaded, alternating between sending and receiving as appropriate for the protocol. 每个端都可以是单线程的,可以根据协议在发送和接收之间交替进行。

  2. 'How do you abort the reading threads?` You don't. “你如何中止阅读线程?”你没有。 If you are indeed dedicating a whole thread to reading from the socket (and that's really not very good design), then the thread simply exits when it sees a receive operation complete with 0 bytes as the length. 如果确实要将整个线程专用于从套接字读取(那的确不是很好的设计),那么当线程看到接收操作的长度为0字节时,该线程就会退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM