Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Error: This socket has been ended by the other party

I have setup a simple server and client, however whenever I close the client, it seems not possible to reconnect. Here's my client:

    const net = require('net');
    var client = net.connect({port: 8080, host: '127.0.0.1'});
    var response = '';
    // events
    client.on('data', function(chunk) { response += chunk });
    client.on('end', function() { 
        console.log(response);
        client.end() 
     });
    // main execution
    client.write('test');

And here's my server:

    const net = require('net');
    var server = net.createServer();
    server.listen(8080, '127.0.0.1');
    server.on('connection', function(sock) {
        sock.on('data', function(chunk) {
            sock.write('test received');
            sock.end();
        });
    });

This is just outline code representing my issue. When I execute my client the first time, everything works correctly. However, when I execute it again, the server outputs the error mentioned in the title and crashes. The same happens if I remove 'client.end()' and instead Ctrl+C out of the client program to cause it to end.

My understanding of sockets is that they represent endpoints in a stream between the client and the server. When that stream is no longer necessary (i.e, when the client does what it needs to do), I want that stream to be completely removed. I would think that calling end() on both the client and server endpoints of that single stream would achieve this, like sending two FIN messages, but as explained it does not. The reasons I want to do this are so: (a) the client file will actually finish execution and (b) the server will no longer have its socket endpoint of that stream in its system/waste resources listening to it.

Any insight into the source of my problem would be appreciated.

like image 887
Philip Avatar asked Sep 05 '25 03:09

Philip


1 Answers

You can check if socket is not destroyed before writing.

if (!socket.destroyed) socket.write("something");
like image 188
Amith Avatar answered Sep 07 '25 19:09

Amith