与ReadAsync / WriteAsync的双向通信(网络流)

时间:2018-06-27 23:49:35

标签: c# asynchronous networking networkstream

我有一个TCP服务器(基于Arduino)接受我通过WriteAsync发送的命令,然后等待确认ReadAsync(即ACK),然后使用ReadAsync接收更多数据。

到目前为止,太好了。在执行此操作时,我使用互斥锁锁定了网络流。

但是,有时我会从服务器获得“推送”更新,这意味着服务器发送了一些我不需要的信息(我想避免与Arduino进行轮询-它已经很忙了...)。我的问题是:我该如何处理?

如何将命令后的阅读命令与新闻的“一般收听”分开?毕竟,什么时候有数据可读取没有事件?有一个“永无止境的任务”可以连续检查是否有要读取的数据并且互斥锁没有锁定=是否没有其他读取操作正在进行?

       // We lock the stream.
        await mutex.WaitAsync().ConfigureAwait(false);
        try
        {
            try
            {
                await stream.WriteAsync(writebuf, 0, writebuf.Length);// TODO: Try this: .ConfigureAwait(false);

                var byteCount = await stream.ReadAsync(ack, 0, ack.Length);

                if (ack[0] != 10)
                {
                    throw new System.IO.IOException("No acknowledgement received from Arduino!");
                }

                byteCount = await stream.ReadAsync(readbuf, 0, readbuf.Length);

                bool readBack1 = Convert.ToBoolean(readbuf[1]);
                bool readBack2 = Convert.ToBoolean(readbuf[2]);
                bool readBack3 = Convert.ToBoolean(readbuf[3]);
                bool readBack4 = Convert.ToBoolean(readbuf[4]);

                if (readBack1 != Valve1Enabled)
                    SetProperty(ref valve1Enabled, readBack1, "Valve1Enabled");
                if (readBack2 != Valve2Enabled)
                    SetProperty(ref valve2Enabled, readBack2, "Valve2Enabled");
                if (readBack3 != Valve3Enabled)
                    SetProperty(ref valve3Enabled, readBack3, "Valve3Enabled");
                if (readBack4 != Valve4Enabled)
                    SetProperty(ref valve4Enabled, readBack4, "Valve4Enabled");
            }
            // Sending failed.
            catch (System.IO.IOException e)
            {
                // TODO: Do the error handling through IObservable.
                // Apart from that, we don't care about anything. Disconnect.
                Disconnect();
            }

        }
        finally
        {
            mutex.Release();
        }

谢谢!

0 个答案:

没有答案