Skip to content

Instantly share code, notes, and snippets.

@robzeh
Last active March 30, 2021 01:23
Show Gist options
  • Save robzeh/2e21066c995c26584be532a4369541f6 to your computer and use it in GitHub Desktop.
Save robzeh/2e21066c995c26584be532a4369541f6 to your computer and use it in GitHub Desktop.
ES6 Socket.io server structure
import { createServer } from 'http';
import { Server, Socket } from 'socket-io';
import express from 'express';
import * as Socket from './socket';
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
// options
});
const { joinRoom } = Socket.default(io);
io.on('connection', (socket: Socket) => {
socket.on('JOIN_ROOM', joinRoom);
});
httpServer.listen(4000, () => {
console.log('Listening on port 4000');
});
import { Server, Socket } from 'socket-io';
export default function (io: Server) {
// roomId parameter and callback function
const joinRoom = function (roomId: string, cb: (res: boolean) => void) {
const socket: Socket = this; // hence, an arrow function will not work
socket.join(roomId);
io.in(roomId).emit('USER_JOIN', socket.id);
cb(true);
};
// other functions
return {
joinRoom
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment