0

I am trying to build a mere client/server tcp connection in C#

Here is the server code snippet:

try
{
    
    var iPAddress = IPAddress.Parse("127.0.0.1");
    var tcpListener = new TcpListener(iPAddress, 8001);
    tcpListener.Start();

    Console.WriteLine("The server is running and listening to the port 8001.");
    Console.WriteLine($"The local End point is: {tcpListener.LocalEndpoint}");
    Console.WriteLine("Waiting for a connection.....");

    var newClient = tcpListener.AcceptTcpClient();
                    
    while (true)
    {
        var rStream = new StreamReader(newClient.GetStream());
        
        var receivedObjDto = JsonConvert.DeserializeObject<ObjDto>(rStream.ReadLine());
        Total += receivedObjDto.Order;
        Console.WriteLine($"message from {newClient.Client.RemoteEndPoint}: {receivedObjDto.Message}, order: {receivedObjDto.Order}, New Total: {Total}");
        
    }
    ...
}
catch (Exception e)
{
    Console.WriteLine(e);
    throw;
}

and the client code snippet :

...
var streamWriter = new StreamWriter(this.tcpConn.GetStream());

var objDto = new ObjDto(message, orderValue);
if (this.tcpConn == null)
{
    MessageBox.Show("Connection not established", "test", MessageBoxButton.OK, MessageBoxImage.Error);
    return;
}

streamWriter.WriteLine(JsonConvert.SerializeObject(objDto));
...

I cannot figure why it is not working.

While debugging I can see on the server side (after client is connected and send a message) that the code is not doing anything else after the line :

var receivedObjDto = JsonConvert.DeserializeObject<ObjDto>(rStream.ReadLine());

(most likely waiting for the line to end ?)

I made it work by closing the streamWriter in the client code but I think this is not the proper way to do :

streamWriter.WriteLine(JsonConvert.SerializeObject(objDto));
streamWriter.close()

Any ideas ? comments ?

Cervelle
  • 5
  • 1
  • 1
  • 4
  • Does this answer your question? [StreamReader.ReadLine and CR](https://stackoverflow.com/questions/1099953/streamreader-readline-and-cr) – NibblyPig Aug 01 '21 at 17:43
  • Since I am using streamWriter.WriteLine and the doc mention : "Writes the specified data, followed by the current line terminator, to the standard output stream." I don't think it does. Am I missing something ? – Cervelle Aug 01 '21 at 17:58
  • 1
    Finaly made it work replacing streamWriter.close(); with streamWriter.Flush();. It seems to be related with cache within Stream – Cervelle Aug 01 '21 at 20:38

0 Answers0