我有一个类实例,我在其中管理登录/心跳以及实际工作项数据包在tcp客户端上的发送接收。
问题是当我尝试并行调用ProcessCommand时出现错误
System.IO.IOException:无法从传输连接中读取数据:连接尝试失败,因为一段时间后被连接方未正确响应,或者由于连接的主机未能响应而建立的连接失败。 ---> System.Net.Sockets.SocketException:连接尝试失败,因为一段时间后连接方未正确响应,或者由于连接的主机未能响应而建立连接失败
public class TcpCommunicationManager
{
private TcpClient client = null;
public TcpCommunicationManager(string ip, int port)
{
Ip = ip;
Port = port;
}
public SSMIResponse ProcessCommand(SSMIRequest request)
{
SSMIResponse response = new SSMIResponse();
if (request.CmdType == CommandType.Login)
{
client = new TcpClient(Ip, Port);
}
response.RequestedCommand = GetCommandTextFromRequest(request);
byte[] buf = Encoding.ASCII.GetBytes(response.RequestedCommand);
var stream = client.GetStream();
request.RequestTime = DateTime.Now;
var result = stream.WriteAsync(buf, 0, buf.Length);
Console.WriteLine("Request Command:" + response.RequestedCommand);
response.SendSuccess = true;
var data = new Byte[1024];
stream.ReadTimeout = 1000 * 5; //5 seconds
// Read the first batch of the TcpServer response bytes.
var bytes = stream.Read(data, 0, data.Length);
response.ResponseTime = DateTime.Now;
response.ResponseRawResultPacket = Encoding.ASCII.GetString(data, 0, bytes);
ProcessResponseResult(request, response);
Console.WriteLine("Response Received:" + response.ResponseRawResultPacket + Environment.NewLine);
return response;
}
}