1

我有以下 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) {
        }
    });
}
4

0 回答 0