Search code examples
javascriptc#network-programminglistener

Why does netcat work just fine when using my listener but it doesnt work when I use JS


I wrote a C# listener that listens on a port and prints everything it recieves, and it works perfectly but when i used a JS client to send that data something get recieved but nothing gets written to the console

My C# code:

while (true)
{
    TcpClient client = null;
    NetworkStream stream = null;

    try
    {
        client = listener.AcceptTcpClient();
        stream = client.GetStream();

        using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = false })
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.ASCII))
            {
                while (true)
                {
                    string inputLine = "";
                    while (inputLine != null)
                    {
                        inputLine = reader.ReadLine();
                        Console.WriteLine(inputLine);
                        Console.WriteLine(Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(inputLine)));
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        if (stream != null)
        {
            stream.Close();
        }
        if (client != null)
        {
            client.Close();
        }
    }

    Console.WriteLine("Verbinding met client verbroken");
}
const net = require('net');

const client = new net.Socket();

client.connect(1234, '192.168.2.13', () => {
  console.log('Connected to server');
  client.write("Hello server\r");
});


I tried running a netcat listener and that worked with my JS program, I also set breakpoints in my code and concluded that when i send something with my JS code it indeed gets recieved by my server but not processed.


Solution

  • Your server/listener tries to read a complete line ('reader.ReadLine()').

    This means, your JS client must send some "line end" marker. "Line end" is newline '\n' (although documentation specifies apparently non-working alternatives).

    So socket.write("Hello server\n") should work.