在typescript中的模块之间共享socket.io

时间:2018-04-05 21:52:23

标签: node.js sockets socket.io

我已经阅读了几个不同方法的示例,以便在模块之间共享socket.io连接,但我似乎无法将所有部分组合在一起来构建它。

我有一个SocketConnection类,我希望在所有代码中共享它。

import * as sio from 'socket.io';

export class SocketConnection {
    private static instance: SocketConnection;
    server: any;

    private constructor(server) {
        this.server = server;
    }
    static getInstance(server) {
        if (!SocketConnection.instance) {
            SocketConnection.instance = new SocketConnection(server);
            const io = sio(server);
            io.on('connection', (socket) => {
                console.log('conncted sockets');
                socket.emit('jobResult', { result: 'emitting startup!' });
            });
        }
        return SocketConnection.instance;
    }
}

然后在我的app.ts中,我这样使用它:

// app.ts
// express app
const server = app.listen(param);
import { SocketConnection } from './integrationJobs/socketConnection';
const io = SocketConnection.getInstance(server);

// Now pass the resulting "io" into the job where I need to use socket.io
import { CourseListJob } from './integrationJobs/courseList';
const courseListJob = new CourseListJob(io);
const job = courseListJob.runJob();

我调用需要套接字的作业的最后一段代码:

// courseList.ts
export class CourseListJob {
    io: any;

    public constructor(io) {
        this.io = io;
    }

    public async runJob() {

          this.io.emit('progressMessage', 'Hello');
    }
}

不幸的是,我得到了这个: TypeError:this.io.emit不是函数

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我通过修改我的SocketConnection类来解决这个问题:

import * as sio from 'socket.io';

export class SocketConnection {
    private static instance: SocketConnection;
    server: any;

    private constructor(server) {
        this.server = server;
    }
    public static GetSocket(server) {
        const io = sio(server);
        io.on('connection', (socket) => {
            console.log('conncted SocketConnection sockets');
            socket.emit('jobResult', { result: 'emitting startup!' });
        });
        return io;
    }
}

在我的app.ts中,我这样使用它:

import { SocketConnection } from './integrationJobs/socketConnection';
const io = SocketConnection.GetSocket(server);


import * as courseList from './integrationJobs/courseList';
courseList.register(io);

import * as courseEnrollment from './integrationJobs/courseEnrollment';
courseEnrollment.register(io);

在我需要套接字的任何代码中,我只是这样做:

import * as sio from 'socket.io';

let io = null;

export function register(foo) {
    io = foo;
}

export class CourseListJob {
    public async runJob() {
    }
}