Tutorial: sync

sync

Client

var socket = io();
let state = new State();

let server_updates = [];

socket.on("connected", id => {
    socket.on("update", state => {
        server_updates.push(state);
    });

    socket.on("state", s => {
        state.init(s.def, s.data);
    })
});

// in your render-loop:
while (server_updates.length) state.update(server_updates.shift());

Server

//state.js
let state = new State();

state.registry.register(null, {
    players: new Map()
}, "game");

state.registry.register(null, {
    x: 0,
    y: 0
}, "player");

module.exports = state;

//player.js
const state = require("./state");

class Player {
    constructor(socket, id) {
        state.sync(this, "player");

        this.id = id;
        this.socket = socket;
    }

    update(dt) {
        //update logic
    }

    onConnect() {
        this.socket.emit("connected", this.id);
    }
}

//game.js
const { nanoid } = require("nanoid");

const state = require("./state");
const Player = require("./player");

class Game {
    constructor(io) {
        state.sync(this);

        this.io = io;
        this.init();

        this.loop = new Loop(dt => {
            this.update(dt);
        }, 50);
    }

    init() {
        this.io.on('connection', (socket) => {
            let player = new Player(socket, nanoid());
            player.onConnect();
            this.players.set(player.id, player);

            //send the initial state to the client
            socket.emit("state", {
                def: state.getSyncDefinition(),
                data: state.getData(this)
            });

            socket.on('disconnect', () => {
                this.players.delete(player.id);
            });
        });
    }

    update(dt) {
        //update the players
        this.players.forEach((player) => {
            player.update(dt);
        });

        //broadcast the changes
        let changes = state.getChanges(this);
        if (!changes.length) return;

        this.players.forEach((player) => {
            player.socket.emit("update", changes);
        });
    }
}