Last active
June 4, 2019 14:08
-
-
Save terence410/964ad8162cc347a8f5d7f5f9ff2c693c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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