How to create a two-way connection using TcpListener and TcpClient?

I have a situation where I need to send and receive information in parallel.
My protocol can determine the read port and write port.

I currently have the following code:

public void Listen() { ThreadPool.SetMinThreads(50, 50); listener.Start(); while (true) { var context = new ListeningContext(listener.AcceptTcpClient(), WritePort); } } 

How can I create another listener from TcpClient that I pass?

+4
source share
2 answers
An object

A TcpClient wraps a NetworkStream object. You use the GetStream() TcpClient to access the NetworkStream object, which is then used to read data and write data to the network. The MSDN article for NetworkStream says the following:

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for write operations and one unique thread for read operations, there will be no crosstalk between read and write streams and no synchronization is required.

Use the TcpListener object to listen for incoming connections. Use the TcpClient object returned from the call in AcceptTcpClient() to communicate (read and write) with the remote endpoint.

+14
source

A TCP connection is a full duplex channel , see here . You do not need a separate port or anything else.

+4
source

Source: https://habr.com/ru/post/1332128/


All Articles