full duplex Tcp data exchange c#

1.4k views Asked by At

I have a full duplex connection between two hosts that exchange datas with a thread that always listen on NetworkStream.Read(). How can I close gracefully the connection avoiding:

1- the deadlock of the two side read() function

2- the abort() of reading threads [closing they safely]

I think closing the connection with SocketShutdown.Send but how it works? It unlock the Read() on the other side.. There are not many things in the documentation.

Thak you

1

There are 1 answers

2
Peter Duniho On

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. But if the defined protocol is a straightforward request/response protocol (e.g. HTTP), even that's not strictly required. 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.