【发布时间】:2016-06-07 09:30:47
【问题描述】:
因此,如果使用socket.io 中的示例,但将io.on 函数放入app.get,则听众会增加。我怎样才能正确解决这个问题?我使用了多种解决方案,但它们更像是“胶带”而不是正确的解决方案。
例如
socket.removeAllListeners();
或
function socketio() {
var counter = 1;
io.on('connection', function (socket) {
if (!(counter)) {
counter--;
socket.emit('news', {hello: 'world'}, function () {
});
socket.on('my other event', function (data) {
console.log(data);
});
}
});
}
感谢和抱歉我的英语。
服务器代码:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.use(express.static(__dirname + '/public'));
function socketio() {
io.on('connection', function (socket) {
socket.emit('news', {hello: 'world'}, function () {
});
socket.on('my other event', function (data) {
console.log(data);
});
});
}
app.get('/', function (req, res) {
socketio();
res.render('socket.jade');
});
客户端代码
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' }, function(){
});
});
第一页重新加载后
Server console.log
{ my: 'data' }
Client console.log
Object { hello: "world" }
第二次重载
Server console.log
{ my: 'data' }
{ my: 'data' }
{ my: 'data' }
{ my: 'data' }
Client console.log
Object { hello: "world" }
Object { hello: "world" }
等等……
【问题讨论】:
标签: javascript node.js express socket.io