这是我第一次使用node.js/socket.io,并且对于所有套接字的“connect”事件触发都有点麻烦。我遵循聊天应用程序示例,然后尝试添加一个功能,而不是在用户连接或断开连接时在控制台中显示,而是在屏幕上显示它。Socket.io connect event not firing
对于所有选项卡(如果我有多个选项卡向聊天应用程序开放),断开连接事件触发,但连接事件似乎只对当前选项卡触发。
服务器(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');
});
客户端(浏览次数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>