How to create a duplex connection using TcpListener and TcpClient?

。_饼干妹妹 提交于 2019-12-30 03:37:12

问题


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?


回答1:


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.




回答2:


TCP connection is a full-duplex pipe, take a look here. You don't need a separate port or anything else.



来源:https://stackoverflow.com/questions/4442504/how-to-create-a-duplex-connection-using-tcplistener-and-tcpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!