index.js 1.9 KB

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