Socket.io-在服务器和客户端之间同步数据

时间:2019-11-12 21:33:49

标签: javascript jquery node.js socket.io express.io

第一次使用节点js,我正在编写一个我和朋友之间供私人使用的应用程序,我的朋友可以随时加入。

是否可能使服务器具有对象数组a.e.带有n个项目的“ franksLibrary”

,并且用户能够阅读和修改“ franksLibrary”?

当前我要做的是在用户网页中设置“ franksLibrary”,并发送franksLibrary和所有其他var来通过socket.io进行同步

index.js是服务器代码, index.html是交付给用户的

例如index.js

var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg, usr){
    io.emit('chat message',msg, usr);
  });

});
http.listen(3000, function(){
  console.log('listening on *:3000');
});

示例index.html:

    var franksLibrary = [{
            "book1":"title of book 1"
        },
        {
            "book2":"title of book 2"
        }];

   socket.on('chat message', function(franksL /*,more variables*/){
       franksLibrary = franksL
    });

    synch = function(){
        socket.emit('chat message', franksLibrary /*,more variables*/);
    }

    removeBook = function(object, from){
        var a = object;
        var index = from.indexOf(a);
        from.splice(index,1);
        synch();
    }

1 个答案:

答案 0 :(得分:1)

franksLibraryindex.html移到index.js。然后,在服务器上的connection回调中,将chat message和数据一起发送到新连接的客户端。

index.js

var franksLibrary = [{
  "book1": "title of book 1"
},
{
  "book2": "title of book 2"
}];

io.on('connection', function(socket) {
  socket.emit('chat message', franksLibrary);
  socket.on('chat message', function(data) {
    franksLibrary = data;
    socket.broadcast.emit('chat message', franksLibrary);
  });
});

index.html

// initialize variable
var franksLibrary = [];

const socket = io();

socket.on('chat message', function(franksL) {
  franksLibrary = franksL;
});

const synch = function(){
  socket.emit('chat message', franksLibrary);
};

const removeBook = function(object, from) {
  var a = object;
  var index = from.indexOf(a);
  from.splice(index,1);
  synch();
};