Skip to content

Instantly share code, notes, and snippets.



Created Jul 31, 2019
What would you like to do?
socket class to use in node server
import * as socketio from '';
import { Server } from 'http';
import { logger } from '../../common/logger';
import { server } from '../../server';
* Represents a socket server instance.
* This class wraps the final technology you will use to implements
* sockets, eg.: socket-io
* We export an instance and not the class becouse in that way we can do the import
* and get a working and initialized instance everywhere in the app, eg.: chatApis.ts
* in other way we must store the reference and pass it to each part of the app that require that.
* TODO: falta resolver el problema mencionado en server.ts sobre instancias de app,
* socket y pm2.
class Socket {
private io: SocketIO.Server;
* Creates the necesary stuffs to get a working socket connection.
* @param server If not specified a new server will be created
* to be binded by the socket.
init(server?: Server) {
if (!server) {
server = server || new Server();
const port = 3002;
server.listen(port, () => {`socket server running on ${port}...`);
} else {`socket server binded to existing server on port ${server.address().port}`);
} = socketio(server);
// MemcachedStore({
// hosts: 'localhost:11211'
// }));'connect', (socket: any) => {
onConnect(socket: any) {'onconnection');
socket.on('message', this.onMessage.bind(this));
socket.on('disconnect', this.onDisconnect.bind(this));
onMessage(m: string) {`onmessage ${JSON.stringify(m)}`);'message', process.env.NODE_APP_INSTANCE);
onDisconnect(x: any) {`disconnected ${x}`);
sendMessage(message: string) {'message', message);
export const socket = new Socket();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment