如何在循环中处理异步tcpClient连接

时间:2019-03-24 08:49:26

标签: c# loops asynchronous tcpclient

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

对于受I / O限制的异步操作,我主要遵循this!并根据他写的内容实施。这是我实现的。

 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);
                    }
            });
    } 

即使我在听设备也无法连接到设备,我也没有得到任何回应。它只是卡住了,什么也不打印。我不知道问题是什么。

任何帮助表示赞赏。

0 个答案:

没有答案
相关问题