简体   繁体   中英

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.

is it possible to have the server have an object array ae 'franksLibrary' with n items

and the users be able to read and modify '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

index.js is the server code, index.html is what is delivered to the user

examle 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:

    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 . Then, in the connection callback on the server, send chat message with the data to the newly connected client.

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();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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