12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- var WebSocket = require("ws");
- var EventEmitter = require("events");
-
- exports = module.exports = new EventEmitter();
- exports.init = init;
- exports.error = error;
- exports.sendGameStopped = sendGameStopped;
- exports.sendGameStart = sendGameStart;
- exports.sendGameList = sendGameList;
-
- var wss;
-
- function onmessage(msg) {
- console.log("Received", msg);
- var obj = JSON.parse(msg);
-
- switch (obj.cmd) {
- case "run":
- return exports.emit("run", obj.name);
-
- default:
- console.error("Received unknown command:", obj.cmd);
- }
- }
-
- function send(obj) {
- var msg = JSON.stringify(obj);
- console.log("Sending", msg);
- wss.clients.forEach(client => {
- if (client.readyState === WebSocket.OPEN)
- client.send(msg);
- });
- }
-
- function init(port, cb) {
- wss = new WebSocket.Server({ host: "127.0.0.1", port }, cb);
-
- wss.on("connection", sock => {
- exports.emit("connection");
- sock.on("message", onmessage);
- });
- }
-
- function sendGameStopped() {
- send({ cmd: "ongamestopped" });
- }
-
- function sendGameStart() {
- send({ cmd: "ongamestart" });
- }
-
- function sendGameList(games) {
- send({ cmd: "ongamelist", games });
- }
-
- function error(msg) {
- send({ cmd: "onerror", msg });
- }
|