无法同时写入和读取网络流c#
我有一个程序,它使用TCP客户端和网络流来接收来自外部IP的消息。消息不断被发送,程序将这些消息转换为用户更可读的格式 但是,IP需要每8秒接收一条keep alive消息以保持连接打开 我似乎很难在阅读信息的同时向流中写入信息。我的印象是,只要它们在不同的线程上,你就可以对流进行读写 计时器运行后,调用写入keep alive消息的方法,我收到错误:无法从传输连接读取数据:已建立的连接已被主机中的软件中止。在调用write to stream方法后尝试读取字节时,会发生此错误 下面是我的代码。这是主要问题:无法同时写入和读取网络流c#,c#,multithreading,networkstream,C#,Multithreading,Networkstream,我有一个程序,它使用TCP客户端和网络流来接收来自外部IP的消息。消息不断被发送,程序将这些消息转换为用户更可读的格式 但是,IP需要每8秒接收一条keep alive消息以保持连接打开 我似乎很难在阅读信息的同时向流中写入信息。我的印象是,只要它们在不同的线程上,你就可以对流进行读写 计时器运行后,调用写入keep alive消息的方法,我收到错误:无法从传输连接读取数据:已建立的连接已被主机中的软件中止。在调用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 ReadInandOutputToTextBoxIfInvoke()中的读取
{
while(运行)
{
字符串消息=”;
int x=0;
int start=35;
int消息长度;
int numberOfMessages;
//NetworkStream nwStream=client.GetStream();
尝试
{
而((x=nwStream.ReadByte())!=start){if(x==-1){continue;}}//如果它不是以#开头,或者已经过了,则中断
//读入消息头,消息头的长度大于消息数
messageLength=nwStream.ReadByte();
numberOfMessages=nwStream.ReadByte();
string messagereceived=新字符串(readMessage(nwStream,messageLength-1));
string[]messages=messagereceived.Split(新字符[]{'|'},StringSplitOptions.RemoveEmptyEntries);
for(int i=0;i
我删除了该方法的一部分,该方法将消息翻译为不相关的内容
这是计时器已过时调用的代码:
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();
}
}
private void KeepAlive(NetworkStream Ns,System.Timers.Timer MyTimer)
{
字节[]toSend=新字节[]{35,51,49,42,124};
尝试
{
for(int i=0;i
我现在已经解决了我的问题。有两个因素阻止程序正常工作
现在它工作得很好。感谢所有试图提供帮助的人。我很困惑,为什么你需要每8秒发送一条消息来保持连接的活动状态,这是不是在另一端每8秒侦听一次?@Jaxi我正在通话的设备如果在设定的时间内没有收到保持活动状态的消息,就会关闭连接使用锁可能会有帮助吗?