Skip to content

Instantly share code, notes, and snippets.

@michaelerobertsjr
Last active October 12, 2017 16:33
Show Gist options
  • Save michaelerobertsjr/3a2685b6b012ddfcfc48eb2a255a1eb5 to your computer and use it in GitHub Desktop.
Save michaelerobertsjr/3a2685b6b012ddfcfc48eb2a255a1eb5 to your computer and use it in GitHub Desktop.
socket server with express
const Server = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', (socket) => {
console.log(`Connection detected: ${socket.client.id}`);
socket.use(([name, data], next) => {
if (data.auth === process.env.SOCKET_KEY) {
return next();
}
console.log(`Auth failure detected: ${socket.client.id}`);
socket.disconnect();
return false;
});
socket.on('event', (event) => {
socketEvents.eventHandler(socket, event);
});
socket.on('action', (action) => {
socketEvents.actionHandler(socket, action);
});
});
const server = require('./server/app');
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
console.log(art);
console.log(`SERVER LISTENING: ${PORT}`);
});
const eventHandler = (socket, event) => {
socket.emit('event:ack', event);
};
const actionHandler = (socket, action) => {
const { type, payload } = action;
switch (type) {
case SERVER_HELLO:
console.log('Got hello payload!', payload);
socket.emit('action', { type: 'MESSAGE', payload: 'good day!' });
break;
case SERVER_TEST_PASSED:
const grader = new Grader(payload.userId, payload.fullName, payload.projectName);
console.log(`SOCKET ACTION HANDLER: TESTS PASSED ==> ${payload.userId}, ${payload.fullName}, ${payload.projectName}`);
grader
.grade()
.then(results => socket.emit('action', { type: 'MESSAGE', payload: `statement posted, statementId: ${results}` }))
.catch(err => socket.emit('action', { type: 'MESSAGE', payload: `statement posting error: ${err}` }));
break;
default:
break;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment