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 ?