Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a duplex connection using TcpListener and TcpClient?

I have a situation where I need to send and receive information parallelly.
My protocol can define a read port and a 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 the TcpClient I am passing?

like image 815
the_drow Avatar asked Dec 03 '22 03:12

the_drow


1 Answers

A TcpClient object wraps a NetworkStream object. You use the GetStream() method of TcpClient to access the NetworkStream object, which is then used to read data from 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 the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

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

like image 112
Matt Davis Avatar answered Dec 04 '22 16:12

Matt Davis