我正在使用网络流向服务器发送命令并接收数据。出于某种原因,我没有收到所有数据。我试图在无限循环中保持连接打开,并在下一次迭代中看到接收到的数据。奇怪的是,当我不使用PORT 80网络流表现良好并正确接收数据时。
这是我的接收功能。
public static string SendRecieveString(string hostname, int port, string message, bool stripHeaderFromRespose = true)
{
//Printer.print("TCP Socket: Attempting Connection to server: " + hostname + "@" + port + " with header: " + message, PrintingSeverities.Info);
//using (WebClient client = new WebClient())
//{
// Printer.print("Send/Recieve communicating with header: " + "http://" + hostname + message + ":" + port, PrintingSeverities.Debug);
// string htmlCode = client.DownloadString("http://" + hostname + message + ":" + port);
// Printer.print("Raw Page: \n " + htmlCode, PrintingSeverities.Debug);
// return htmlCode;
//}
#region v1
try
{
string page = String.Empty;
using (TcpClient clientHandler = new TcpClient(hostname, port))
{
if (clientHandler.Connected) {
using (NetworkStream clientStream = clientHandler.GetStream())
{
if (!clientStream.CanRead || !clientStream.CanWrite)
{
Printer.print("TCP Socket: Stream cannont preform read/write", PrintingSeverities.Warning);
throw new Exception("TCP Socket: Stream cannont preform read/write");
}
Byte[] bytes2send = Encoding.ASCII.GetBytes(message);
clientStream.Write(bytes2send, 0, bytes2send.Length);
do
{
Byte[] bytesReceived = new Byte[clientHandler.ReceiveBufferSize];
int streamReceived = clientStream.Read(bytesReceived, 0, bytesReceived.Length);
page += Encoding.ASCII.GetString(bytesReceived, 0, streamReceived);
Printer.print("Stream size: " + streamReceived);
} while (clientStream.DataAvailable);
Printer.print("Raw Page: " + page, PrintingSeverities.Debug);
}
if (stripHeaderFromRespose)
{
string HTTPHeaderDelimiter = "\r\n\r\n";
if (page.IndexOf("HTTP/1.1 200 OK") > -1)
page = page.Substring(page.IndexOf(HTTPHeaderDelimiter) + HTTPHeaderDelimiter.Length);
}
}
else
{
Printer.print("TCP Socket: Could not connect to server", PrintingSeverities.Warning);
throw new Exception("TCP Socket: Could not connect to server");
}
}
Printer.print("TCP Socket: Returning Page: " + page, PrintingSeverities.Debug);
return page;
}
catch (Exception ex)
{
throw ex;
}
#endregion
我收到了这个: 原始页面: HTTP / 1.1 200好的 缓存控制:无存储 内容类型:text / xml 内容长度:399
[结束] - >虽然我应该收到: 原始页面:
HTTP/1.1 200 OK
Cache-control: no-store
Content-type: text/xml
Content-length: 399
<?xml version="1.0" encoding="utf-8" ?> <datavalues><relay1state>0</relay1state><relay2state>1</relay2state><reboot1state>0</reboot1state><reboot2state>0</reboot2state><failures1>0</failures1><failures2>0</failures2><rbtAttempts1>0</rbtAttempts1><rbtAttempts2>0</rbtAttempts2><totalreboots1>0</totalreboots1><totalreboots2>0</totalreboots2><serialNumber>00:0C:C8:02:B9:92</serialNumber></datavalues>"
答案 0 :(得分:1)
更新#10! :)
看起来另一个主题同意我的评估如下。 有关其他信息,请参阅this StackOverFlow帖子。
问题似乎在于您正在检查是否可以从异步源获得数据。 (换句话说,答案可能是“不尚未”。)
<强>解决方案:强>
使用WebClient库为您完成工作:
var webClient = new WebClient();
string readHtml = webClient.DownloadString(hostname);
坚持您原来提出的方法,尝试通过
阅读