首页 > 解决方案 > 如何在循环中处理异步 tcpClient 连接

问题描述

我有几个在同一个端口上监听的设备。我只是发送不同的消息,如 A、B、C 并获取一些环境值。所有设备都有不同的 IP。我想要做的是与设备建立异步连接并以同步方式将消息发送到传感器。

对于 I/O 绑定的异步操作,我主要遵循这个!并根据他写的内容实施。这是我实施的。

 static async Task CallingMethodAsync()
    {
        List<string> devices = new List<string>
        {
            "10.20.30.116",
            "127.0.0.1",
            "10.20.30.149",
            "10.20.30.100"
        };

        List<string> messages = new List<string>
        {
            "A",
            "B",
            "C",
            "D",
        };
        List<Task> deviceList = new List<Task>();

        foreach (var device in devices)
        {

            foreach (var message in messages )
            {
                deviceList.Add(ConnectAsClientAsync(device, message));
            }
        }
        await Task.WhenAll(deviceList);
    }


static  Task ConnectAsClientAsync(string device,string  message)
    {
            return  new Task(  () =>
            {

                byte[] ClientRequestBytes = Encoding.UTF8.GetBytes(message);

                    try
                    {
                        using (var tcpClient = new TcpClient(device, 11000))
                        {

                            Console.WriteLine("Connected ->>" + device + " from port:" + port);


                            using (var networkStream = tcpClient.GetStream())
                            {
                                networkStream.Write(ClientRequestBytes, 0, ClientRequestBytes.Length);
                                byte[] bytesToRead = new byte[tcpClient.ReceiveBufferSize];
                                int bytesRead = nwStream.Read(bytesToRead, 0, tcpClient.ReceiveBufferSize);
                                var response = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
                                   Console.WriteLine("response ->>" + response+ " from device:"+device);
                            }
                        }
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine("No Answer!! from ->>" + device + " from port:" + port);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Not Connected ->>" + device + " from port:" + port);
                    }
            });
    } 

即使设备正在收听,我也无法连接到设备,我也没有收到蚂蚁响应。它只是卡住了,不打印任何东西。我不知道问题是什么。

任何帮助表示赞赏。

标签: c#loopsasynchronoustcpclient

解决方案


推荐阅读