简体   繁体   English

监听来自 2 个 TcpClient 实例对相同 IP 的响应,但端口不同

[英]Listen to responses from 2 TcpClient instances against the same IP, but different ports

I'm working on a TCP connection where my client connects to a server's IP on 2 different ports.我正在处理 TCP 连接,我的客户端在 2 个不同的端口上连接到服务器的 IP。 So I have 2 instances of TcpClient objects, one connecting to the IP on port 9000 and the other on port 9001.所以我有 2 个 TcpClient 对象实例,一个连接到端口 9000 上的 IP,另一个连接到端口 9001。

The aim of 2 connections is that the server uses the active connection on port 9000 to give certain responses to the client frequently, and the client uses these responses to form and send a request on port 9001 . 2个连接的目的是服务器使用端口 9000上的活动连接频繁地向客户端发出某些响应,客户端使用这些响应在端口 9001上形成和发送请求。

Now, the first time I connect on 9000, I get a response, I then form a request and fire off via 9001. Now I have a feeling I'm doing something wrong with the way I'm managing asynchronous requests to both ports, but I can't figure an alternate way of doing this:现在,我第一次在 9000 上连接时,我得到一个响应,然后我形成一个请求并通过 9001 启动。现在我感觉我在管理对两个端口的异步请求的方式上做错了,但我想不出另一种方法:

    IPAddress IPAddress = IPAddress.Parse("192.168.1.10");

    public static async Task ConnectToPort9000()
    {
        TcpClient TcpClient1 = new TcpClient();
        try
        {
            await TcpClient1.ConnectAsync(IPAddress, 9000);
            if (TcpClient1.Connected)
            {
                byte[] Buffer = new byte[1024];
                while (await TcpClient1.GetStream().ReadAsync(Buffer, 0, Buffer.Length) > 0)
                {
                    //Server returns a message on this port
                    string Port9000Response = Encoding.UTF8.GetString(Buffer, 0, Buffer.Length);

                    //Setting ConfigureAwait(false) so that any further responses returned
                    //on this port can be dealt with
                    await Task.Run(async () =>
                    {
                        await SendRequestToPort9001BasedOnResponseAsync(Port9000Response);
                    }).ConfigureAwait(false);
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    private async Task SendRequestToPort9001BasedOnResponseAsync(string Port9000Response)
    {
        //Open connection on port 9001 and send request
        TcpClient TcpClient2 = new TcpClient();
        await TcpClient2.ConnectAsync(IPAddress, 9001);

        if (TcpClient2.Connected)
        {
            //Handle each string response differently
            if (Port9000Response == "X")
            {
                //Form a new request message to send on port 9001
                string _NewRequestMesssage = "Y";
                byte[] RequestData = Encoding.UTF8.GetBytes(_NewRequestMesssage);
                new SocketAsyncEventArgs().SetBuffer(RequestData, 0, RequestData.Length);
                await TcpClient2.GetStream().WriteAsync(RequestData, 0, RequestData.Length);
                await TcpClient2.GetStream().FlushAsync();
                //Handle any responses on this port

                //At this point, based on the request message sent on this port 9001
                //server sends another response on **port 9000** that needs separately dealing with
                //so the while condition in the previous method should receive a response and continue handling that response again
            }
            else if (Port9000Response == "A")
            {
                //Do something else
            }
        }
    }

The issue I am having at the moment is, after I send the request on port 9001, when processing any response messages on port 9001, the server has already sent me a response on port 9000, but my while loop on the first method isn't getting triggered, and it seems like that's because it's still executing the second method to process request/response on port 9001. I tried using ConfigureAwait(false) to basically fire and forget , but it doesn't seem to be working.我现在遇到的问题是,在我在端口 9001 上发送请求后,在处理端口 9001 上的任何响应消息时,服务器已经在端口 9000 上向我发送了响应,但是我在第一种方法上的 while 循环不是t 被触发,这似乎是因为它仍在执行第二种方法来处理端口 9001 上的请求/响应。我尝试使用 ConfigureAwait(false) 基本上触发并忘记,但它似乎不起作用。 Am I handling asynchronous processes the wrong way?我是否以错误的方式处理异步进程? Or should I look at alternatives such as action/delegates?或者我应该看看行动/代表等替代方案?

The aim of 2 connections is that the server uses the active connection on port 9000 to give certain responses to the client frequently, and the client uses these responses to form and send a request on port 9001. 2个连接的目的是服务器使用9000端口上的活动连接频繁地给客户端一些响应,客户端使用这些响应在9001端口形成和发送请求。

Please don't do this.请不要这样做。 Socket programming is hard enough without making it extremely more complicated with multiple connections.套接字编程已经够难了,而且不会因为多个连接而变得极其复杂。 Error handling becomes harder, detection of half-open connections becomes harder (or impossible), and communication deadlocks are harder to avoid.错误处理变得更难,半开连接的检测变得更难(或不可能),通信死锁更难避免。

Each socket connection is already bidirectional;每个套接字连接已经是双向的; it already has two independent streams.它已经有两个独立的流。 The only thing you need to do is always be reading, and send as necessary.您唯一需要做的就是始终阅读并根据需要发送。 The read and write streams are independent, so keep your reads and writes independent.读写流是独立的,因此请保持读写独立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TcpClient上的不同端口上有多个流? - Multiple streams on TcpClient on different ports? TcpClient可以连接到2个不同的端口吗? - Can a TcpClient be connected to 2 different ports? 如何在同一网络中具有不同 IP 的设备和计算机上使用 tcplistener 和 tcpclient? - How to use tcplistener and tcpclient on device and computer with different ip in same Network? 在 C# 中与来自不同 ApiController 实例的串行端口通信 - Communicate with Serial Ports from different ApiController instances in C# C#,tcpClient到多个IP地址但在同一端口上 - C#, tcpClient to Multiple IP Address but on the same port C#,我如何从 TcpClient 获取 ip 地址? - C#, how do i get an ip address, from a TcpClient? 从另一台机器上收听来自 IP 的消息 - Listen to message from an IP from another machine 侦听一系列UDP端口 - Listen to a range of UDP ports 在服务结构的不同端口上运行的多个红隼无状态服务实例 - Multiple kestrel stateless service instances running on different ports in service fabric 是否可以从同一个应用程序登录到两个不同的 Application Insights 实例? - Is it possible to log to two different instances of Application Insights from the same Application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM