12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- var server = require("http").createServer();
- module.exports = class WebSocketServer {
- constructor() {
- this._pageMap = new Map();
- this._roomIDS = new Map();
- this._roomPerson = new Map()
- this._users = [];
- }
- create() {
- this.io = require("socket.io")(server, {
- path: "/vr-node",
- serveClient: false,
- // below are engine.IO options
- pingInterval: 10000,
- pingTimeout: 5000,
- cookie: false,
- });
- server.listen(3000, { origins: "*" });
- this.io.on("connection", (socket) => {
- let user = socket.handshake.query
- this._users.push(user)
- const roomId = user['roomId']
- console.log(user)
- socket.join(roomId, () => {
- let roomsPerson = this._roomPerson.get(roomId) || []
- roomsPerson.push(user)
- this._roomPerson.set(roomId, roomsPerson)
- // 只派发非小程序端的socket连接数及其user数据
- if (!user[isClient]) {
- this.io.to(roomId).emit('vr_request', { persons: roomsPerson.filter(item => !item.isClient) });
- }
- });
- socket.on('startCall', () => {
- socket.broadcast.to(roomId).emit('answer', { user })
- })
- socket.on('stopCall', () => {
- socket.broadcast.to(roomId).emit('putup', { user })
- })
- socket.on("getJson", (data) => {
- if (roomId) {
- this.io.to(roomId).emit("action", data.content.action);
- this.io.to(roomId).emit("vr_response", data);
- }
- });
- console.log("WebSocket服务端建立完毕");
- socket.on("disconnect", (reason) => {
- let roomsPerson = this._roomPerson.get(roomId) || []
- // 断开连接的把roomsPerson中的user去掉
- roomsPerson = roomsPerson.filter(item => item !== user)
- this._roomPerson.set(roomId, roomsPerson)
- if (!user.isClient) {
- this.io.to(roomId).emit('vr_request', { persons: roomsPerson.filter(item => !item.isClient) });
- console.log("关闭连接", reason);
- }
- });
- socket.on("error", function (reason) {
- console.log("异常关闭", reason)
- });
- return this;
- })
- }
- close() {
- this.server.disconnect(true);
- }
- };
|