Nodejs:此套接字已关闭

时间:2013-09-03 12:10:08

标签: node.js sockets

我在Node.js中使用tcp套接字与Java客户端进行通信。

请参阅下面的基本服务器实现:

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);

出于某种原因,有时我会收到此错误:

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

它发生在这条线上:

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

任何想法如何防止这种情况发生?

2 个答案:

答案 0 :(得分:6)

或使用client.writable来检测套接字是否可用。

    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.");
        }
    }

答案 1 :(得分:2)

试试此代码

选项1

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) {

    }
 }

选项2

在套接字上附加错误事件侦听器。

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

});