Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 361
Psylution Avatar asked Oct 16 '15 22:10

Psylution


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

C is an imperative, procedural language in the ALGOL tradition. It has a static type system. In C, all executable code is contained within subroutines (also called "functions", though not in the sense of functional programming).

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


1 Answers

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.

like image 159
ipavlu Avatar answered Oct 07 '22 23:10

ipavlu