无法同时写入和读取网络流 c#



我有一个程序,它使用TCPClient和Network Stream从外部IP接收消息。消息不断发送,程序将这些消息转换为用户更易读的格式。

但是,IP 需要每 8 秒接收一次保持活动状态消息,以保持连接打开。

我似乎难以阅读消息,同时写入流。我的印象是,只要它们在不同的线程上,您就可以读取和写入流。

计时器过去后,调用了写入保持活动状态消息的方法,我收到错误:无法从传输连接读取数据:主机中的软件中止了已建立的连接。当它在调用写入流方法后尝试读取字节时,会发生此错误。

下面是我的代码。这是主要的:

public MainWindow()
{
InitializeComponent();
client.Connect(address, port);
nwStream = client.GetStream();
System.Timers.Timer newTimer = new System.Timers.Timer(8000);
newTimer.Elapsed += delegate { KeepAlive(nwStream, newTimer); };
newTimer.Start();
Thread t = new Thread(ReadInandOutputToTextBoxIfInvoke);
t.Start();
}

以下是从流中读取的线程和方法:

private void ReadInandOutputToTextBoxIfInvoke()
{
while (run)
{
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];

我删除了该方法的一部分,该方法可以翻译消息,因为它不相关。

这是计时器经过时调用的代码:

private void KeepAlive(NetworkStream Ns, System.Timers.Timer MyTimer)
{
byte[] toSend = new byte[] { 35, 51, 49, 42, 124 };
try
{
for (int i = 0; i < toSend.Length; i++)
{
Ns.WriteByte(toSend[i]);
Ns.Flush();
}
}
catch
{
MyTimer.Close();
}
}

我现在已经解决了我的问题。有两个因素阻止程序正常工作。

  1. 使用锁后,错误停止出现。
  2. 我发送到设备的消息格式不正确 - 它必须是十六进制

它现在工作得很好。感谢所有试图提供帮助的人。

最新更新