【问题标题】:Unable to write and read to a network stream at the same time c#无法同时写入和读取网络流c#
【发布时间】: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


【解决方案1】:

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

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

现在可以完美运行了。感谢所有试图提供帮助的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多