简体   繁体   中英

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.

We're basically working on a TCP Server/Client Application, where the Server is written in Java and the Client is written in C#. I'm on the Java Side, and I'm using seperated in and output streams for my buffers.

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. 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. From there TcpClient.GetStream() , returning 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) .

Similarly, multiple concurrent writes have to be synchronized by lock(objWrites) .

MSDN says , that it is guaranteed.

Please note, that I made it clear, that reads and writes have different locks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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