Skip to content

Instantly share code, notes, and snippets.

@daniellizik
Created June 2, 2016 19:56
Show Gist options
  • Save daniellizik/a05a0f146eaa1c675391d44a2a74da76 to your computer and use it in GitHub Desktop.
Save daniellizik/a05a0f146eaa1c675391d44a2a74da76 to your computer and use it in GitHub Desktop.
basic express/socketio setup
<html>
<head>
<title></title>
</head>
<body>
<input id="chat" />
<div id="display"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.min.js"></script>
<script src="index.js"></script>
</body>
</html>
// backend index
const Server = require('./Server');
const server = new Server();
server.serveStatic([ {path: __dirname + '/public', publicPath: '/'} ]);
server.sockets({
'CHATTING_UP': (io, socket, msg, type) => {
io.emit('CHATTING_DOWN', `${msg} ${new Date().getTime()}`);
}
});
server.listen(9999);
// front end index
const socket = io.connect();
socket.on('CHATTING_DOWN', res => {
const disp = document.querySelector('#display');
disp.textContent += res;
});
document.querySelector('#chat').addEventListener('keyup', e => {
socket.emit('CHATTING_UP', e.target.value);
});
'use strict';
const path = require('path');
const express = require('express');
const http = require('http');
const io = require('socket.io');
class Server {
constructor(config) {
this.rooms = [];
this.app = express();
this.server = http.Server(this.app);
this.socket = io;
this.io = this.socket(this.server);
}
middleware(device) {
if (Array.isArray(device)) {
device.forEach(this.middleware.bind(this));
} else if (typeof device === 'function') {
this.app.use(device());
} else {
this.app.use(device);
}
}
serveStatic(asset) {
if (Array.isArray(asset)) {
return asset.forEach(this.serveStatic.bind(this));
}
if (typeof asset === 'object') {
this.app.use(asset.publicPath, express.static(asset.path));
}
}
listen(port) {
this.server.listen(port, () => console.log(`listening on ${port}`));
return {
close: () => this.server.close()
}
}
sockets(hooks) {
this.io.on('connection', socket => {
this.rooms.push(socket);
for (let type in hooks) {
socket.on(type, msg => hooks[type](this.io, socket, msg, type));
}
});
}
}
module.exports = Server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment