index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // socket
  2. const { Server } = require("socket.io");
  3. const { fork } = require('child_process');
  4. class ContrlServer {
  5. constructor() {
  6. this.Contrl = null
  7. this.socket = null
  8. this.initSoket();
  9. }
  10. // socket 服务
  11. initSoket() {
  12. const io = new Server({
  13. cors: {
  14. origin: ["*"],
  15. },
  16. });
  17. // 中间件
  18. io.use((socket, next) => {
  19. const { roomID, name } = socket.handshake.auth;
  20. if (roomID !== "feiCar" && (name !== "car" || name !== "ctrl"))
  21. return next(new Error("invalid token"));
  22. socket.join(roomID);
  23. socket.broadcast.to(roomID).emit('joined', { name: name, roomID: roomID })
  24. next();
  25. });
  26. io.on("connection", (socket) => {
  27. const { roomID, name } = socket.handshake.auth;
  28. console.log(name, "连接");
  29. // 监听其它信息
  30. socket.on("msg", (data) => {
  31. // 转发消息
  32. socket.broadcast.to(roomID).emit("msg", data);
  33. });
  34. // 监听离开
  35. socket.on("disconnect", () => {
  36. // 转发离开
  37. socket.broadcast.to(roomID).emit("leaved", {
  38. name: name,
  39. roomID: roomID
  40. });
  41. socket.leave(roomID)
  42. this.socket = null
  43. console.log(name, '断开连接');
  44. })
  45. // 控制服务
  46. this.socket = socket
  47. });
  48. io.listen(7896)
  49. console.log("服务开启成功7896");
  50. this.initContrl()
  51. }
  52. // 控制服务
  53. initContrl() {
  54. this.Contrl = fork('./contrl.js')
  55. this.Contrl.on('message', (msg) => {
  56. if (this.socket && this.socket.connected) {
  57. console.log('用户连接可发送', msg);
  58. this.socket.emit('msg',JSON.parse(msg))
  59. }
  60. console.log('contrl message: ' , msg);
  61. })
  62. }
  63. }
  64. new ContrlServer();