這是我第一次使用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>