Skip to content

Instantly share code, notes, and snippets.

@terence410
Last active June 4, 2019 14:08
Show Gist options
  • Save terence410/964ad8162cc347a8f5d7f5f9ff2c693c to your computer and use it in GitHub Desktop.
Save terence410/964ad8162cc347a8f5d7f5f9ff2c693c to your computer and use it in GitHub Desktop.
//import {SocketServer} from "./SocketServer";
//const server: SocketServer = new SocketServer();
//server.start();
import Debug from "debug";
import {EventEmitter} from "events";
import * as Http from "http";
import * as SocketIo from "socket.io";
const debug = Debug("app:SocketServer");
export class SocketServer extends EventEmitter {
// private _express: Express.Application;
private _http: Http.Server;
private _io: SocketIo.Server;
private _httpPort: number;
private _socketOptions = {
path: "/socket.io",
pingInterval: 10 * 1000,
pingTimeout: 5000,
transports: ["websocket"],
};
constructor() {
super();
this._httpPort = Number(process.env.PORT || "80");
// http
this._http = Http.createServer(this._httpHandler);
// socket
this._io = SocketIo.default(this._http, this._socketOptions);
this._io.use(this._onHandshake);
this._io.on("connection", this._onConnect);
}
public start() {
this._http.listen(this._httpPort, "0.0.0.0", () => {
debug(`http listening on ${this._httpPort}`);
});
}
public broadcast() {
this._io.emit("message", {message: "Hello World!"});
}
private _httpHandler = (req: Http.IncomingMessage, res: Http.ServerResponse) => {
debug("http request");
res.end("hello world");
}
private _onHandshake = (socket: SocketIo.Socket, next: (err?: any) => void) => {
if (socket.handshake.query.userId) {
return next();
} else {
debug(`handshake error: userId not exist`);
return next(new Error("authentication error"));
}
}
private _onConnect = (socket: SocketIo.Socket) => {
debug(`userId: ${socket.handshake.query.userId} connected`);
socket.on("disconnect", this._onDisconnect.bind(this, socket));
}
private _onDisconnect = (socket: SocketIo.Socket) => {
debug(`userId: ${socket.handshake.query.userId} disconnected`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment