正确的Socket.io套接字断开

时间:2014-02-03 19:43:31

标签: javascript node.js sockets socket.io

所以我有一个节点js客户端:

var io = require('socket.io-client');
var serverUrl = 'http://localhost:8080/w';
var socket = io.connect(serverUrl);

socket.emit('call', "Watchdog is talking.", function(resp) {
    console.log("Boss said : " + resp); 
});

socket.on('disconnect', function() {
    console.log('disconnect called');
    process.exit();
});

和这样的节点js服务器:

var express         = require ('express'),
    app             = express().listen(8080),
    io              = require('socket.io').listen(app),
    watchdog        = io.of('/w');

//Listener for watchdog socket namespace
    watchdog.on('connection', function(socket) {
        socket.on('call', function(msg, fn) {
            console.log("Watchdog 's saying : " + msg);
            fn("Good job son.");
            socket.disconnect();
        });
    });

我希望客户端在发送数据后停止,所以我在'disconnect'事件上调用process.exit()但这似乎不是一个结束套接字连接的正确方法,因为我得到“套接字错误错误:阅读ECONNRESET“。我怎样才能实现正确的断开连接? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您在服务器端以错误的方式使用自定义事件。在服务器端做类似的事情:

watchdog.on('connection', function(socket) {
    socket.on('call', function(msg, fn) {
        console.log("Watchdog 's saying : " + msg);
        fn("Good job son.");
        socket.emit('disconnect_fired', {});
    });
});

并在客户端执行此操作:

socket.on('disconnect_fired', function(data){
  socket.disconnect();
});