c# - 如何在循环中处理异步 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);
}
});
}
即使设备正在收听,我也无法连接到设备,我也没有收到蚂蚁响应。它只是卡住了,不打印任何东西。我不知道问题是什么。
任何帮助表示赞赏。
解决方案
推荐阅读
- stm32 - STM32L053 上的 EEPROM 仿真器
- sql - 如何在sql中获取计数为0的列
- android - 如何使用导航从其他片段隐藏主机活动中的视图
- ios - 使用 Flutter 插件作为子框架开发伞式框架
- django - 字段是必需的,即使它已在序列化程序中明确设置为不需要
- python - 如何在数据框中定义df
- amazon-web-services - Terraform 局部变量不适用于我的“或”运算符
- python - abaqus python(2.7版)使用multiprocessing.Pool(),没有响应
- sql-server - 这些简单的 T-SQL 更新语句是否更新相同?
- verilog - uvm 入门,第 11 章,没有为形式参数“父级”指定实际值