Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: This socket is closed

I am using tcp sockets in Node.js to communicate with a Java client.

See my very basic server implementation below:

var server = my_http.createServer();
echo.installHandlers(server, {
    prefix: '/echo'
});
server.listen(8000, '0.0.0.0');

var socketServer = net.createServer(function (socket) {

    // Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    sockets[socket.name] = socket;

    // Handle incoming messages from clients.
    socket.on('data', function (data) {

        try {
            var obj = JSON.parse(data);

            if (obj.type == "sendMessage") {
                broadcast("{\"id\":\"1\", \"msg\": \"" + obj.msg + "\", \"name\": \"" + obj.name + "\", \"time\": \"" + getDateTime() + "\"}\n", socket);

            }
        } catch (er) {

        }
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
        try {
            clients.splice(clients.indexOf(socket), 1);
        } catch (err) {

        }
    });

    // Send a message 

    function broadcast(message, sender) {
        try {
            clients.forEach(function (client) {
                client.write(message); // ERROR IS HERE
            });
        } catch (ee) {

        }
    }

    return socket;
}).listen(8080);

For some reason sometimes i get this error:

events.js:71 throw arguments[1]; // Unhandled 'error' event ^ Error: This socket is closed.

Its happening on this line:

client.write(message); // ERROR IS HERE

Any ideas how to prevent this from happening?

like image 707
Alosyius Avatar asked Sep 03 '13 12:09

Alosyius


2 Answers

or use client.writable to detect if the socket available.

    clients.forEach(function (client) {
        try {
            if (client.writable) {
                clientwrite("are u alive");
            } else {
                console.log('client is not writable');
            }
        } catch (err) {
            console.log("cannot send message.");
        }
    }
like image 97
fxp Avatar answered Sep 19 '22 20:09

fxp


Try this code

Option1

function broadcast(message, sender) {
    try {
        clients.forEach(function (client) {
            if(client._handle){ // ensure there is still underlying handle
               client.write(message); // ERROR IS HERE
            }
        });
    } catch (ee) {

    }
 }

Option2

Attach error event listener on socket.

Socket.on('error',function(){
   console.log("%j", arguments);

});
like image 2
Chandu Avatar answered Sep 21 '22 20:09

Chandu