通过套接字客户端

时间:2017-08-14 15:15:37

标签: javascript mysql node.js sockets socket.io

我有以下问题。如何从另一个JS文件中向套接字返回一个新值?

App.js

io.on('connection', function (socket) {
    socket.currentRoomId = 0;
    socket.currentRoomName = "Loading...";
    socket.currentRoomOwner = 1;
    socket.currentRoomEntry = 1.1;
});

RoomManager.js

adapter.query(sql, function(err, rows) {
    rows.forEach( (row) => { 
       socket.currentRoomId = parseInt(row.Id);
       socket.currentRoomName = row.room_name;
       socket.currentRoomOwner = row.room_owner;
       socket.currentRoomEntry = row.room_entry;
    });
});

问候。

1 个答案:

答案 0 :(得分:0)

您必须emitlisten这样,

<强> RoomManager.js

adapter.query(sql, function(err, rows) {
    rows.forEach( (row) => { 
       // emit setCurrentData with the row data
       socket.emit('setCurrentData', { data: row });
    });
});

<强> App.js

io.on('connection', function (socket) {
    socket.currentRoomId = 0;
    socket.currentRoomName = "Loading...";
    socket.currentRoomOwner = 1;
    socket.currentRoomEntry = 1.1;

    // listen to setCurrentData 
    socket.on('setCurrentData', function (row) {
       socket.currentRoomId = parseInt(row.data.Id);
       socket.currentRoomName = row.data.room_name;
       socket.currentRoomOwner = row.data.room_owner;
       socket.currentRoomEntry = row.data.room_entry;
    });
});