C# TcpClient不从服务器(.Net core)读取响应
我目前正在从事一个网络项目,该项目需要向服务器发送请求并从服务器获得响应。服务器由第三方公司托管,因此我无法直接访问服务器,但可以请求服务器日志。根据该日志,我的请求已成功发送到服务器,服务器也会响应。但我这边没有得到回应。我还使用数据包发送器工具来检查响应,它也没有收到任何响应。这里可能有什么问题?我的代码没有问题,因为我连接到不同的服务器时会收到响应。此问题仅在一台特定服务器上发生。谢谢大家 //建立TCP连接C# TcpClient不从服务器(.Net core)读取响应,c#,.net-core,network-programming,tcpclient,tcpserver,C#,.net Core,Network Programming,Tcpclient,Tcpserver,我目前正在从事一个网络项目,该项目需要向服务器发送请求并从服务器获得响应。服务器由第三方公司托管,因此我无法直接访问服务器,但可以请求服务器日志。根据该日志,我的请求已成功发送到服务器,服务器也会响应。但我这边没有得到回应。我还使用数据包发送器工具来检查响应,它也没有收到任何响应。这里可能有什么问题?我的代码没有问题,因为我连接到不同的服务器时会收到响应。此问题仅在一台特定服务器上发生。谢谢大家 //建立TCP连接 public async Task<TcpClient> Conne
public async Task<TcpClient> ConnectAsync(TcpClient tcpClient)
{
string xmlMessageServer = _configuration["XmlMessageStrings:xmlMessageServer"];
string xmlMessagePort = _configuration["XmlMessageStrings:xmlMessagePort"];
var errorLog = NLogBuilder.ConfigureNLog("NLog.config").GetLogger("debitcardErrorLog");
try
{
await tcpClient.ConnectAsync(xmlMessageServer, Convert.ToInt32(xmlMessagePort));
errorLog.Info(tcpClient.GetHashCode());
return tcpClient;
}
catch (SocketException ex)
{
errorLog.Error(ex.Message); // log error
throw ex;
}
}
Encoding.ASCII.GetString(bufferSize,0,0)
Count==0?”int-xmlResponse=stream.Read(bufferSize,0,bufferSize.Length);//从switchware读取xml响应
“-重要一点:不,它没有;它至少读取一个字节(或失败);TCP是一种流协议-不保证在另一端如何发送或接收整个帧方面获得相同的有效负载布局-如果要在同一管道上接收多条消息,则需要添加自己的帧协议;如果您正在处理UTF8之类的问题,这包括接收部分字符(不同的读取操作中的不同字节部分)对不起,我的错误是字符串xmlresponsemsgsgacii=Encoding.ASCII.GetString(bufferSize,0,bufferSize.Length);但是仍然没有得到响应。@BuddhikaNelumxmlResponse
的值是多少?当你说“仍然没有得到回应”时,到底发生了什么?它只是在读取时永远阻塞吗?或者你得到了什么?如果是,什么?注意:您甚至应该只查看字节[0,xmlResponse)
,这样最多应该是GetString(bufferSize,0,xmlResponse)
(对于本地人来说,这些名称非常混乱!bufferSize
不是大小,xmlResponse
不是xml!)@MarcGravel不,读取时不会阻塞,但需要2-3分钟的时间。服务器日志证明他们成功地收到了我的请求,并发送了响应。问题是,在读取响应时,xmlResponse的值始终为0。
try
{
TcpClient tcpClient = new TcpClient();
await _connectWithTcpServer.ConnectAsync(tcpClient);
if (tcpClient.Connected)
{
debitcardRequestLog.Info("Tcp Client Connected"); // check if client connected
NetworkStream stream = tcpClient.GetStream();
debitcardRequestLog.Info(xmlMessage); // log xmlMessage
byte[] xmlRequest = Encoding.ASCII.GetBytes(xmlMessage); // converts the xmlRequest into a byte array
stream.Write(xmlRequest, 0, xmlRequest.Length); //writes the xmlRequest into the stream
byte[] bufferSize = new byte[tcpClient.ReceiveBufferSize]; //converts the bufferSize into a byte array
int xmlResponse = stream.Read(bufferSize, 0, bufferSize.Length); //reads the xml response from switchware
if (xmlResponse == 0)
{
errorLog.Error("0 bytes received from server");
}
string xmlResponseMsg = string.Empty;
string xmlResponseMsgASCII = Encoding.ASCII.GetString(bufferSize, 0, 0); // decode the byte array into a string
debitcardResponseLog.Info(xmlResponseMsgASCII);
fromSwitchwareMessage = xmlResponseMsgASCII;
}
}
catch (Exception ex)
{
errorLog.Error(ex.Message); // log error
throw ex;
}