Home > Software engineering >  C# socket - how to correctly handle line ending
C# socket - how to correctly handle line ending

Time:12-26

I received an 3rd party exe which listens on port 1234 and expects number e.g 5000 ended with new line character and returns output for it

but for some reason e.g when I send just 0 then it gets stuck and when I restart both my listener and this exe then I feel like I received previous response

Or I send 1 it returns e.g TRUE and when I send 1 once again then it returns FALSE, so it seems to do not handle those inputs separately, as if that was not aware of it being OTHER message

I guess there's some problem with my code, but I can't know because I don't have code of this 3rd party.

I believe I handle line ending wrong

using System.Net;   
using System.Text;
using System.Net.Sockets;


var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
socket.Connect(remoteEndPoint);

while (true)
{
    string s = Console.ReadLine();
    byte[] byData = Encoding.ASCII.GetBytes(s   "\r\n"); // I tried also \r \\r \n \\n \\r\\n
    socket.Send(byData);

    byte[] buffer = new byte[1024];

    int length = socket.Receive(buffer);
    char[] chars = new char[length];

    Encoding.UTF8.GetChars(buffer, 0, length, chars, 0);
    Console.WriteLine(new string(chars));
}   

CodePudding user response:

This is a bit as searching in he dark; but you could try to append the NULL character \0.

So basically: \n\0 or \r\n\0. NULL character is sometimes used (in)correctly to determine the end of a string, especially in older C like systems.

You can read more about it here: https://en.m.wikipedia.org/wiki/Null_character

  • Related