如何使用TcpListener和TcpClient创建双工连接? [英] How to create a duplex connection using TcpListener and TcpClient?

查看:96
本文介绍了如何使用TcpListener和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.

我目前有以下代码:

public void Listen()
{
    ThreadPool.SetMinThreads(50, 50);
    listener.Start();

    while (true)
    {
        var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
    }
}

如何从我传递的TcpClient中创建另一个侦听器?

How can I create another listener from the TcpClient I am passing?

推荐答案

TcpClient对象包装NetworkStream对象.您可以使用TcpClientGetStream()方法访问NetworkStream对象,该对象随后用于从网络读取数据或将数据写入网络. NetworkStream 的MSDN文章说,以下:

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:

可以进行读写操作 同时执行 NetworkStream类的实例 无需同步. 只要有一个唯一的线程 用于写操作和一个 读取操作的唯一线程, 不会有交叉干扰 在读写线程之间,没有 需要同步.

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.

使用TcpListener对象来侦听传入的连接.使用从对AcceptTcpClient()的调用返回的TcpClient对象与远程端点进行通信(读写).

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.

这篇关于如何使用TcpListener和TcpClient创建双工连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆