Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created June 2, 2015 21:59
Show Gist options
  • Select an option

  • Save mohayonao/66a0df9ffb767be297cf to your computer and use it in GitHub Desktop.

Select an option

Save mohayonao/66a0df9ffb767be297cf to your computer and use it in GitHub Desktop.
import EventEmitter from "./EventEmitter";
import Session from "./Session";
export default class Application extends EventEmitter {
constructor(io) {
super();
this.io = io;
this.slots = [];
io.on("connect", (socket) => {
this.appendSocket(socket);
});
}
numberOfSessions() {
return this.slots.reduce((counter, session) => {
return counter + (session ? 1 : 0);
}, 0);
}
appendSocket(socket) {
let session = new Session(socket);
socket.on("disconnect", () => {
let index = this.slots.indexOf(session);
if (index !== -1) {
this.slots[index] = null;
session.dispose();
}
});
socket.on("dispatch", (payload = {}) => {
payload.session = session;
this.dispatch(payload);
});
let index = this.slots.indexOf(null);
if (index !== -1) {
this.slots[index] = session;
} else {
this.slots.push(session);
}
}
dispatch(payload = {}) {
this.emit("dispatch", payload);
}
}
import http from "http";
import path from "path";
import express from "express";
import socketio from "socket.io";
import MyApplication from "./app/MyApplication";
let app = express();
let server = http.createServer(app);
let io = socketio(server);
app.use(express.static(path.join(__dirname, "../../public")));
server.listen(config.SERVER_PORT, () => {
console.log("Listening on port %d", server.address().port);
});
new MyApplication(io).run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment