我有一个程序,它使用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;
}
}
案例陈述只是翻译消息所以可能不相关。
更新 - 我在我的catch语句中添加了一个console.writeline来输出任何错误,似乎没有出现错误。请参阅下面的编辑:
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;
}
答案 0 :(得分:0)
问题原来是我所说的设备必须在一定时间内收到保持活动消息,否则它会关闭连接。它现在有效 - 我每隔8秒发送一次保持活动消息。