socket.io客户端连接断开连接

时间:2014-07-04 04:43:02

标签: node.js socket.io socket.io-1.0

我无法弄清楚为什么多次断开/连接socket.io连接不起作用?

服务器端代码:

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

客户端代码:

var socket = io();
socket.on('connect', function() {
    console.log("connected from the client side");
});
$('#connect_button').click(function(){
    socket.connect();
});
$('#disconnect_button').click(function(){
    socket.disconnect();
});

它断开连接。但不重新连接。我正在使用Socket.io 1.0。请帮忙。

2 个答案:

答案 0 :(得分:37)

您是否在客户端尝试过此配置?

// 0.9  socket.io version
io.connect(SERVER_IP, {'force new connection': true});

// 1.0 socket.io version
io.connect(SERVER_IP, {'forceNew': true});

答案 1 :(得分:21)

此解决方案基于Jujuleder的回答。显然在socket.io 1.0中,它是“forceNew”而不是“强制新连接” - 两者都有效。

服务器:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendfile('s.html');
});

io.on('connection', function(socket){
    console.log('a user connected: ' + socket.id);
    socket.on('disconnect', function(){
        console.log( socket.name + ' has disconnected from the chat.' + socket.id);
    });
    socket.on('join', function (name) {
        socket.name = name;
        console.log(socket.name + ' joined the chat.');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

客户端(s.html):

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>button{width: 100px;}input{width: 300px;}</style>
</head>
<body>

<ul id="messages"></ul>

<button id="disconnect">disconnect</button>
<button id="connect">connect</button>

<script src="/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

    var socket = io.connect('http://localhost:3000');

    $('#disconnect').click(function(){
        socket.disconnect();
    });
    $('#connect').click(function(){
//        socket.socket.reconnect();
//        socket = io.connect('http://localhost:3000',{'force new connection':true });
        socket = io.connect('http://localhost:3000',{'forceNew':true });
        socket.on('connect', function(msg){
            socket.emit('join', prompt('your name?'));
        });
    });
    socket.on('connect', function(msg){
        socket.emit('join', prompt('your name?'));
    });
    socket.on("disconnect", function(){
        console.log("client disconnected from server");
    });

</script>
</body>
</html>