C#TCP客服端异步读取数据有数据立马返回结果没数据超时返回数据
以下是一个使用异步读取数据的C# TCP客户端代码,当有数据时,立即返回结果,如果没有数据,等待一定时间后超时返回:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class TcpClientAsync
{
private const int ReceiveBufferSize = 1024;
private const int TimeoutMilliseconds = 5000;
public static async Task<string> ReadFromTcpServerAsync(string host, int port)
{
var tcpClient = new TcpClient();
await tcpClient.ConnectAsync(host, port);
byte[] receiveBuffer = new byte[ReceiveBufferSize];
var networkStream = tcpClient.GetStream();
string response = null;
try
{
await networkStream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length);
response = Encoding.ASCII.GetString(receiveBuffer);
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.TimedOut)
{
Console.WriteLine("Timeout occurred while waiting for data.");
}
tcpClient.Close();
return response;
}
}
在上面的代码中,我们使用TcpClient类连接到TCP服务器,并从服务器异步读取数据。我们使用ReadAsync方法来读取数据,如果有数据可用,它将立即返回结果,否则它将等待一定时间(这里是5秒)后超时返回。如果发生超时,我们将打印一条消息并返回null。
注意:上述代码只是一个示例,并且可能需要根据您的需求进行修改。例如,您可能需要在超时前多次尝试读取数据,或者使用更复杂的协议来与服务器通信
原文地址: https://www.cveoy.top/t/topic/fHQ4 著作权归作者所有。请勿转载和采集!