| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- // socket + http
- const { createServer } = require("http");
- const express = require("express");
- const { Server } = require("socket.io");
- const { fork } = require('child_process');
- class VideoServer {
- constructor() {
- this.Contrl = null
- this.socket = null
- this.initSoket();
- }
- // socket 服务
- initSoket() {
- 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
- });
- httpServer.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);
- }
- console.log('contrl message: ' , msg);
- })
- }
- }
- new VideoServer();
|