我有以下nodejs server.js:
var DEFAULT_PORT = 9000,
express = require('express'),
http = require('http'),
socketio = require('socket.io'),
app = express(),
server = http.createServer(app),
io = socketio.listen(server);
server.listen(app.get('port'));
var sockets = {
tickets : {
obj : io.of('/tickets'),
nrusers : 0
}
};
sockets.tickets.obj.on('connection', function (socket) {
socket.on('new_comment', function (data) {
socket.broadcast.emit('server_response', {op : 'updated', msg : data.note_id});
socket.get('room', function(err, room) {
socket.broadcast.to(room).emit('server_response', {op : 'new_comment', msg : {ticket_id : data.ticket_id, note_id : data.note_id}});
});
});
socket.on('details_ticket_join', function (room) {
socket.get('room', function(err, oldRoom) {
socket.set('room', room, function(err) {
socket.join(room);
if (oldRoom) {
socket.leave(oldRoom);
}
socket.emit('server_response', {op : 'join', msg : 'Joined to '+ room});
});
});
});
socket.on('disconnect', function() {
});
});
对于这种情况,我让用户查看故障单详细信息。当用户为故障单添加新评论时,我会通知所有其他已连接的用户并查看相同的故障单详细信息页面。我在没有页面刷新的情况下使用ajax请求加载页面。问题是,当我多次加载票证的详细信息页面时,对于每个加载,我从服务器收到套接字消息,我不明白为什么?
客户详细信息页面代码如下:
var room = 'ticket_'+ id,
MG.sockets : {
tickets : {
obj : ( typeof io == 'object' ? io.connect('http://localhost:9000/tickets') : {} ),
rooms : []
}
};
if ($.inArray(room, MG.sockets.tickets.rooms) == -1) {
MG.sockets.tickets.obj.emit('details_ticket_join', room);
MG.sockets.tickets.rooms.push(room);
}
function commitNote() {
$.ajax({
type: 'POST',
url: urlaction,
data: aData,
processData: false,
contentType: false,
success: function(data) {
if (data != '') {
MG.sockets.tickets.obj.emit('new_comment', {'ticket_id': ticket_id, 'note_id': parseInt(note_id), 'room': room});
}
},
error: function(xhrObject, textStatus, errorThrown) {
}
});
}