简体   繁体   English

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

[英]Socket.io - sync data between server and clients

first time node js, i am writing an app for private use between me and friends where my friends could join in anytime.第一次使用node js,我正在编写一个供我和朋友之间私人使用的应用程序,我的朋友可以随时加入。

is it possible to have the server have an object array ae 'franksLibrary' with n items是否可以让服务器有一个包含 n 个项目的 object 数组 ae 'franksLibrary'

and the users be able to read and modify 'franksLibrary'?用户可以阅读和修改“franksLibrary”吗?

currently what i do is have 'franksLibrary' set in the users webpage and send franksLibrary and all other vars to sync via socket.io目前我所做的是在用户网页中设置“franksLibrary”,并通过 socket.io 发送 franksLibrary 和所有其他变量以同步

index.js is the server code, index.html is what is delivered to the user index.js 是服务器代码,index.html 是交付给用户的

examle index.js示例 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');
});

example index.html:示例索引.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();
    }

Move franksLibrary from index.html to index.js .franksLibraryindex.html移动到index.js Then, in the connection callback on the server, send chat message with the data to the newly connected client.然后,在服务器的connection回调中,将带有数据的chat message发送给新连接的客户端。

index.js 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索引.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();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM