【问题标题】:Socket.io - sync data between server and clientsSocket.io - 在服务器和客户端之间同步数据
【发布时间】:2020-03-08 15:44:36
【问题描述】:

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

是否可以让服务器拥有一个对象数组 a.e. 'franksLibrary' 有 n 个项目

用户可以阅读和修改“franksLibrary”吗?

目前我所做的是在用户网页中设置“franksLibrary”并发送 franksLibrary 和所有其他变量以通过 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();
    }

【问题讨论】:

  • is it possiblecurrently what i do 好的,有什么问题?在minimal reproducible example 中分享相关代码并说明需要改进的地方。
  • 我添加了我的代码的简化版本,我希望变量存储在服务器而不是用户

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


【解决方案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();
};

【讨论】:

  • 谢谢,这正是我想要的,这样我的用户是否重新连接都没关系,它仍然会给出准确的状态
猜你喜欢
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多