简体   繁体   English

C#TcpClient,同时读写流

[英]C# TcpClient, read and write stream simultaneously

I know this kinda question got asked several times already here on SO, but not a single thread addressed that exact same problem which we are facing at the moment. 我知道这个问题已经在SO上多次被问过,但是没有一个线程解决了我们目前面临的完全相同的问题。

We're basically working on a TCP Server/Client Application, where the Server is written in Java and the Client is written in C#. 我们基本上是在使用TCP服务器/客户端应用程序,其中服务器是用Java编写的,客户端是用C#编写的。 I'm on the Java Side, and I'm using seperated in and output streams for my buffers. 我在Java端,我正在为我的缓冲区使用分离和输出流。

Our problem is that if the client receives messages from the server and reads those messages asynchronous out the buffer and tries to write something into it during that process an exception is thrown - no surprise. 我们的问题是,如果客户端从服务器接收消息并从缓冲区中异步读取这些消息并尝试在该过程中写入一些内容,则会抛出异常 - 这并不奇怪。

My question is: What's the way to go in this scenario? 我的问题是:这种情况下的方法是什么? Creating seperated streams? 创建分离的流? We tried that already, but it seemed like C# does not want us to. 我们已经尝试过,但似乎C#不希望我们这样做。 We are in desperate need of a solution here, and any help is greatly appreciated! 我们迫切需要一个解决方案,非常感谢任何帮助!

No, it should work. 不,它应该工作。 What you need is TcpClient , which you probably already have. 你需要的是TcpClient ,你可能已经拥有它。 From there TcpClient.GetStream() , returning NetworkStream . 从那里TcpClient.GetStream() ,返回NetworkStream Then read and write operations can occur concurrently/simultaneously without need for synchronization. 然后,读取和写入操作可以同时/同时发生,而无需同步。 So read and write can occur in same time. 因此读写可以同时发生。

What has to be synchronized is multiple concurrent reads. 必须同步的是多个并发读取。 All concurrent reads have to be synchronised by lock(objReads) . 所有并发读取都必须通过lock(objReads)进行同步。

Similarly, multiple concurrent writes have to be synchronized by lock(objWrites) . 类似地,必须通过lock(objWrites)同步多个并发写入。

MSDN says , that it is guaranteed. MSDN说 ,它是有保证的。

Please note, that I made it clear, that reads and writes have different locks. 请注意,我明确表示,读取和写入具有不同的锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM