如果存在';It’过了一段时间就没有反应了
本文关键字:一段时间 有反应 过了 存在 It 如果 | 更新日期: 2023-09-27 18:21:08
我有以下TAP方法要读取&将数据写入我的套接字端点
private async Task ReadFromAddress(string address)
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(address), 4001);
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
sockets.Add(client);
await client.ConnectTaskAsync(remoteEP);
await ReadAsync(client);
}
private async Task ReadAsync(Socket s)
{
var args = new SocketAsyncEventArgs();
args.SetBuffer(new byte[128], 0, 128);
var awaitable = new SocketAwaitable(args);
while (true)
{
await s.ReceiveAsync(awaitable);
int bytesRead = args.BytesTransferred;
if (bytesRead <= 0) break;
var data = new ArraySegment<byte>(args.Buffer, 0, bytesRead);
AppendLog("RX: " + data.DumpHex());
}
}
public static Task<int> SendAsync(this Socket socket, byte[] buffer, int offset, int count)
{
return Task.Factory.FromAsync<int>(
socket.BeginSend(buffer, offset, count, SocketFlags.None, null, socket),
socket.EndSend);
}
public static Task<int> SendTaskAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags)
{
AsyncCallback nullOp = (i) => { };
IAsyncResult result = socket.BeginSend(buffer, offset, size, flags, nullOp, socket);
// Use overload that takes an IAsyncResult directly
return Task.Factory.FromAsync<int>(result, socket.EndSend);
}
这就是我如何连接到我的IP地址列表
private async void button1_Click(object sender, EventArgs e)
{
var listOfIps = new List<string> { "192.168.168.199", "192.168.168.221" };
await Task.WhenAll(listOfIps.Select(ip => ReadFromAddress(ip)));
}
每次我使用WriteAsync发送一些数据时,我都应该几乎立即得到一些数据。如果可能的话,我应该如何以TAP化的方式扩展我的代码,这样,如果我没有从say。。3秒。。我会再次重新发送数据吗?
这就是我将数据写入特定套接字的方式:
var socket = sockets[i];
var returnMessage =new byte[2];
returnMessage[0] = 0x01;
returnMessage[1] = 0x02;
await socket.WriteAsync(returnMessage);
首先,我建议您不要混合使用不同的异步系统。我建议用TAP方法替换SocketAsyncEventArgs
。
要按照您的建议设置超时,您需要创建另一个层。您当前的代码处理低级读取和写入;您需要一个更高的消息级抽象。