Skip to content

Instantly share code, notes, and snippets.

@StoneyEagle
Last active August 17, 2022 23:46
Show Gist options
  • Save StoneyEagle/a4c4b30067d06feca89f8b36b8ccf80c to your computer and use it in GitHub Desktop.
Save StoneyEagle/a4c4b30067d06feca89f8b36b8ccf80c to your computer and use it in GitHub Desktop.
NodeJs Socket.io template
import http from 'http';
import {socket} from './socket.mjs';
export default async (app) => {
let httpsServer = https.createServer(credentials, app);
httpsServer
.listen(config.secureInternalPort, '0.0.0.0', () => {
console.log(`server running`);
})
.on('error', (err) => {
console.error({
message: 'Sorry Something went wrong starting the secure server',
});
process.exit(1);
});
socket.connect(httpsServer);
}
import { Server } from 'socket.io';
var io = null;
let myClientList = [];
global.socket = [];
global.io = io;
const socketCors = {
cors: {
origin: '*',
methods: 'GET,PUT,POST,DELETE,OPTIONS'.split(','),
credentials: true,
exposedHeaders: ['Content-Length', 'Range'],
acceptRanges: 'byes',
},
}
export const socket = {
connect: function (server) {
io = new Server(server, socketCors);
io.setMaxListeners(300);
io.once('connection', (socket) => {
socket.on('disconnect', () => {
});
});
},
listen: function (event, values) {
if (io) {
io.listen(event, values);
}
},
emit: function (event, values) {
if (io) {
io.emit(event, values);
}
},
use: function (event, values) {
if (io) {
io.sockets.use(event, values);
}
},
on: function (event, values) {
if (io) {
io.on(event, values);
}
},
};
export default socket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment