Socket.io 连接事件未触发

two*_*new 3 node.js socket.io

这是我第一次使用 node.js/socket.io,我在为所有套接字触发 'connect' 事件时遇到了一些麻烦。我遵循了聊天应用程序示例,然后尝试添加一个功能,当用户连接或断开连接时,我不会在控制台中显示它,而是将它显示在屏幕上。

断开连接事件为所有选项卡触发(如果我有多个选项卡打开聊天应用程序),但连接事件似乎只为当前选项卡触发。

服务器 (index.js)

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

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    socket.on('connect', function(){
        io.emit('connect', "A user connected");
    });
    socket.on('disconnect', function(){
        io.emit('disconnect', "A user disconnected");
    });
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});
Run Code Online (Sandbox Code Playgroud)

客户端 (index.html)

<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    var socket = io();
    $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
    });
    socket.on('chat message', function(msg){
       $('#messages').append($('<li>').text(msg));
    });
    socket.on('disconnect', function(msg){
       $('#users').text(msg);
    });
    socket.on('connect', function(msg){
       $('#users').text(msg);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

Pri*_*oka 6

确保您的 socket.io 客户端和服务器与 socket.io 的主要版本相同。例如,在服务器和客户端或 socket.io-client@3 上使用 socket.io@2.3.0。. 在服务器和客户端上。