You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ipc.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var WebSocket = require("ws");
  2. var EventEmitter = require("events");
  3. exports = module.exports = new EventEmitter();
  4. exports.init = init;
  5. exports.error = error;
  6. exports.sendGameStopped = sendGameStopped;
  7. exports.sendGameStart = sendGameStart;
  8. exports.sendGameList = sendGameList;
  9. var wss;
  10. function onmessage(msg) {
  11. console.log("Received", msg);
  12. var obj = JSON.parse(msg);
  13. switch (obj.cmd) {
  14. case "run":
  15. return exports.emit("run", obj.name);
  16. default:
  17. console.error("Received unknown command:", obj.cmd);
  18. }
  19. }
  20. function send(obj) {
  21. var msg = JSON.stringify(obj);
  22. console.log("Sending", msg);
  23. wss.clients.forEach(client => {
  24. if (client.readyState === WebSocket.OPEN)
  25. client.send(msg);
  26. });
  27. }
  28. function init(port, cb) {
  29. wss = new WebSocket.Server({ host: "127.0.0.1", port }, cb);
  30. wss.on("connection", sock => {
  31. exports.emit("connection");
  32. sock.on("message", onmessage);
  33. });
  34. }
  35. function sendGameStopped() {
  36. send({ cmd: "ongamestopped" });
  37. }
  38. function sendGameStart() {
  39. send({ cmd: "ongamestart" });
  40. }
  41. function sendGameList(games) {
  42. send({ cmd: "ongamelist", games });
  43. }
  44. function error(msg) {
  45. send({ cmd: "onerror", msg });
  46. }