Question

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(HOST_IP), HOST_PORT);
Stream stream = client.GetStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
while (true) {
  string line;
  while((line = reader.ReadLine())!=null) {
    Console.WriteLine(line);
  }
  writer.WriteLine(Console.ReadLine());
}

My server sends two strings to the client:

var stream = new NetworkStream(soc);
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true
writer.WriteLine("Welcome: ");
writer.WriteLine("Bla...: ");
reader.ReadLine();

My client get will show

Welcome
Bla..

But it doesn't run the command writer.WriteLine(Console.ReadLine());

Was it helpful?

Solution

You need to decide how this is all going to shutdown, but as indicated in the comments, I'd suggest you use a second thread, to get both sides (the send and receive sides on the client) able to run without blocking:

TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(HOST_IP), HOST_PORT);
Stream stream = client.GetStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
var t = new Thread(() => {
    while(true) {
        writer.WriteLine(Console.ReadLine());
    }
});
t.Start();
while (true) {
  string line;
  while((line = reader.ReadLine())!=null) {
    Console.WriteLine(line);
  }
}

Unlike in your comment, you wouldn't want to create the threads in a loop - there's always a possibility that one side (e.g. receiving from the server) can process multiple times without any work for the other side (sending to the server).

For shutdown, I'd usually create a ManualResetEvent that gets set (by whatever criteria are appropriate) when it's time to shutdown. I'd then make testing the event object the condition for the while loops.

The only issue is that Console.ReadLine() is blocking. So your read console/send to server thread wouldn't see that the shutdown event has been set unless it receives new input. If your read/send thread isn't responsible for initiating shutdown, you could make it a background thread (assuming it doesn't mutate any global state) and then just deal with shutting down your receive/write thread (i.e. the main thread) at an appropriate time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top