| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- // socket | http
- const { createServer } = require("http");
- const express = require("express");
- const { Server } = require("socket.io");
- const { fork } = require('child_process');
- class ContrlServer {
- constructor() {
- this.Contrl = null
- this.socket = null
- this.initSoketHttp();
- }
- // socket 服务
- initSoketHttp() {
- const app = express();
- app.use(express.static("./web"));
- const httpServer = createServer(app);
- const io = new Server(httpServer,{
- cors: {
- origin: ["*"],
- },
- });
- // 中间件
- io.use((socket, next) => {
- const { roomID, name } = socket.handshake.auth;
- if (roomID !== "feiCar" && (name !== "car" || name !== "ctrl"))
- return next(new Error("invalid token"));
- socket.join(roomID);
- socket.broadcast.to(roomID).emit('joined', { name: name, roomID: roomID })
- next();
- });
- io.on("connection", (socket) => {
- const { roomID, name } = socket.handshake.auth;
- console.log(name, "连接");
- // 监听其它信息
- socket.on("msg", (data) => {
- // 转发消息
- socket.broadcast.to(roomID).emit("msg", data);
- });
- // 监听离开
- socket.on("disconnect", () => {
- // 转发离开
- socket.broadcast.to(roomID).emit("leaved", {
- name: name,
- roomID: roomID
- });
- socket.leave(roomID)
- this.socket = null
- console.log(name, '断开连接');
- })
- // 控制服务
- this.socket = socket
- });
- io.listen(7896)
- console.log("服务开启成功7896");
- this.initContrl()
- }
- // 控制服务
- initContrl() {
- this.Contrl = fork('./contrl.js')
- this.Contrl.on('message', (msg) => {
- if (this.socket && this.socket.connected) {
- console.log('用户连接可发送', msg);
- this.socket.emit('msg',JSON.parse(msg))
- }
- console.log('contrl message: ' , msg);
- })
- }
- }
- new ContrlServer();
|