index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 VideoServer {
  7. constructor() {
  8. this.Contrl = null
  9. this.socket = null
  10. this.initSoket();
  11. }
  12. // socket 服务
  13. initSoket() {
  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. httpServer.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. }
  64. console.log('contrl message: ' , msg);
  65. })
  66. }
  67. }
  68. new VideoServer();