网络流似乎停止阅读?
问题描述:
我有一个程序,它使用TCPClient和网络流从ip和端口读取数据。消息不断地以快速的速度发送给程序。该程序旨在读取这些消息,并翻译消息,以便显示为用户提供更易读格式的信息。网络流似乎停止阅读?
这似乎工作正常 - 约60秒。出于某种原因,它似乎停止阅读消息。没有错误消息显示,只是没有新的消息通过。当我停下来并开始程序时,它再次正常工作,直到一分钟左右。
下面是我用过的代码。希望您能够看到我可能出错的地方,这可能会导致流停止收到新消息。在主:
public MainWindow()
{
InitializeComponent();
client.Connect(address, port); //client, address and port are declared as public and static
connected = true;
if (connected == true)
{
readInTxtBox.Text = "Connected";
}
Thread t = new Thread(ReadInandOutputToTextBoxIfInvoke);
t.IsBackground = true;
t.Start(); //the thread is where the messages are read in
}
这是方法:
private void ReadInandOutputToTextBoxIfInvoke()
{
while (true)
{
string message = "";
int x = 0;
int start = 35;
int messageLength;
int numberOfMessages;
NetworkStream nwStream = client.GetStream();
try
{
while ((x = nwStream.ReadByte()) != start) { if (x == -1) { continue; } } //if it doesnt begin with # or has gone over then break
//reads in message header which is length then number of messages
messageLength = nwStream.ReadByte();
numberOfMessages = nwStream.ReadByte();
string messageRecieved = new string(readMessage(nwStream, messageLength - 1));
string[] messages = messageRecieved.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < numberOfMessages; i++)
{
string messageToProcess = messages[i];
char messageType = messageToProcess[0];
switch (messageType)
{
case 'h':
try
{
heightMsg.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch { }
break;
case 'l':
try
{
longWarpHeightMsg.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch { }
break;
case 's':
try
{
status.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch { }
break;
case 'r':
try
{
calibrateMsg.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch { }
break;
default:
break;
}
}
case语句只是翻译的消息,所以可能不会相应和。
更新 - 我已经添加了一个console.writeline到我的catch语句来输出任何错误,似乎没有错误发生。请参阅我所做的编辑如下:
switch (messageType)
{
case 'h':
try
{
heightMsg.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch (Exception e)
{ Console.WriteLine(e.ToString()); }
break;
case 'l':
try
{
longWarpHeightMsg.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch(Exception e) { Console.WriteLine(e.ToString()); }
break;
case 's':
try
{
status.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch(Exception e) { Console.WriteLine(e.ToString()); }
break;
case 'r':
try
{
calibrateMsg.Translate(Utilities.ConvertHexStringToByteArray(messageToProcess.Substring(1)));
}
catch(Exception e) { Console.WriteLine(e.ToString()); }
break;
default:
break;
}
答
的问题竟然是我说话有接收保持一定的时间内活消息的设备,否则关闭连接。现在起作用 - 我每隔8秒发送一次保持活动消息。
嗯,我会*开始*通过删除所有那些空的catch块来隐藏你的任何错误。 (如果出现问题,你是否真的想继续前进而没有任何*问题的指示?) –
会导致网络流停止读取吗? –
尝试使用Console.Writeline追踪问题来自哪里..还监视您的项目性能,如果它是否有变量需要处置或任何。以及你的网络。 –