node socket app新实例范围

时间:2017-09-27 05:13:27

标签: node.js design-patterns ecmascript-6 socket.io

它是一个使用事件基础模式的简单套接字应用程序

const invitation = require('./invitation');
module.exports = function(io){
    io.on('connection', (socket)=>{
        var prepareGame = new PrepareGame(socket)
        socket.on("sendInvitation",(data, ack)=>{
            prepareGame.sendInvitation(data,ack)
        });
    });
}

和prepareGame.js

const events = require('events');
const util = require('util');

class PrepareGame extends events {
    constructor(socket) {
        super();
        this.user = socket.user
        var self = this

        draftInvitation(data){
            this.newInvitation = {
                from_user: self.user.id,
                to_user: data.to_user,
                message:data.message,
                created_at:moment().unix(),
            }
            return this
        };

        self.on("toSocket", (eventName, clientId, data) => {
            console.log(` ===>>>> sending to listener ${eventName}`, clientId);
            var client  = users[clientId]
            if(client)
                client.emit(eventName, data)
        });

    }

    // public function
    sendInvitation(data, ack) {
        // console.log(this);
        var self = this
        data.message = 'New Invitation'
        draftInvitation(data)
        .emit("toSocket", "getInvitation", data.to_user, self.newInvitation)

        setTimeout(()=>{
            data.message = 'Invitation timeout'
            draftInvitation(data)
            .emit("toSocket", "getInvitation", self.user.id, self.newInvitation)
        }, 15000)

        if(typeof ack == 'function')
            ack({
                status:200,
                message: "invitation sent",
            })
    }
}

util.inherits(PrepareGame, events.EventEmitter )

module.exports =  PrepareGame

代码是不同设计模式的总和。它工作正常,但我有一些疑问

  1. io.connection调用一次连接socket和prepareGame 实例创建。考虑两个用户的两个实例然后 调用
  2. 时sendInvitation如何自动绑定正确的实例
  3. 套接字断开时新的prepareGame实例会发生什么?
  4. 我想从socket.on中删除(data, ack)=>{ }封闭器 应该socket.on(" sendInvitation",prepareGame.sendInvitation)然后 如何在sendInvitation函数中管理此引用

0 个答案:

没有答案