【发布时间】:2017-08-04 14:14:27
【问题描述】:
我有一个程序,它使用 TCPClient 和网络流从外部 IP 接收消息。消息不断被发送,程序将这些消息转换为用户更易读的格式。
但是,IP 需要每 8 秒接收一次保持活动消息以保持连接打开。
我似乎难以同时阅读消息和写入流。我的印象是,只要它们在不同的线程上,您就可以读取和写入流。
一旦计时器结束,并且调用写入保持活动消息的方法,我收到错误:无法从传输连接读取数据:已建立的连接被主机中的软件中止. 调用 write to stream 方法后尝试读取字节时会发生此错误。
下面是我的代码。这是主要的:
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();
}
}
【问题讨论】:
-
我很困惑为什么您需要每 8 秒发送一条消息以保持连接处于活动状态,这是另一端每 8 秒侦听一次的东西吗?
-
@Jaxi 我正在与之交谈的设备如果在设定的时间内没有收到保持活动消息,则会关闭连接
-
使用锁可能有帮助吗?
标签: c# multithreading networkstream