Last active
March 30, 2021 01:23
-
-
Save robzeh/2e21066c995c26584be532a4369541f6 to your computer and use it in GitHub Desktop.
ES6 Socket.io server structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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