每个客户端有多个 NetworkStreams

发布于 2025-01-03 14:34:57 字数 768 浏览 1 评论 0原文

我最近开始接触 NetworkStreams,我有一个问题。我当前正在创建一个线程,并处理所有传入的消息。

下面是说明这一点的代码:

client.Connect(serverEndPoint);
clientStream = client.GetStream();
client.NoDelay = true;

ctThread = new Thread(getMessage);
ctThread.Start();  

private void getMessage()
{
    while (true)
    {
        Byte[] data = new Byte[800];
        String responseData = String.Empty;
        Int32 bytes = clientStream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

        MessageReceived(this, new ClientMessageEventArgs(responseData));
    }
}

在上面,我引发了一个事件“MessageReceived”,该事件根据数据包数据进行处理。这很好用,但也有一个单独的情况,我需要在发送请求后立即检索数据。

每个客户端有两个流可以吗?这甚至可以在同一端口上执行吗?这应该如何处理?本质上,我希望能够发送数据,然后立即接收数据(阻塞方式)。

I have recently started getting into NetworkStreams, and I had a question. I am currently creating a thread, and processing all incoming messages as they come in.

Here is the code to illustrate this:

client.Connect(serverEndPoint);
clientStream = client.GetStream();
client.NoDelay = true;

ctThread = new Thread(getMessage);
ctThread.Start();  

private void getMessage()
{
    while (true)
    {
        Byte[] data = new Byte[800];
        String responseData = String.Empty;
        Int32 bytes = clientStream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

        MessageReceived(this, new ClientMessageEventArgs(responseData));
    }
}

In the above, I raise an event "MessageReceived" which is handled according the the packet data. This works great, but also have a seperate case where I need to retrieve data immediately after I send my request.

Is it ok to have two streams per client? Is this even possible to do on the same port? How should this be handled? Essentially, I want to be able to Send and then Receive data immediately after (blocking way).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饭团 2025-01-10 14:34:57

您可以以线程安全的方式独立地从网络流中读取和写入。即从一个线程读取并从另一个线程写入。

如果您查看开源网络通信库networkComms.net,您可以看到这是如何独立实现的发送方法SendPacket() (第 1304 行) 和接收方法 IncomingPacketHandler() (第 802 行)。

MX

You can read and write from network streams independently and in a thread safe manner. i.e. reading from one thread and writing from another.

If you checkout the open source network communication library networkComms.net you can see how this is achieved independently in the sending method SendPacket() (line 1304) and receiving method IncomingPacketHandler() (line 802).

Mx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文