index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var server = require("http").createServer();
  2. module.exports = class WebSocketServer {
  3. constructor() {
  4. this._pageMap = new Map();
  5. this._roomIDS = new Map();
  6. this._roomPerson = new Map()
  7. this._users = [];
  8. }
  9. create() {
  10. this.io = require("socket.io")(server, {
  11. path: "/test",
  12. serveClient: false,
  13. // below are engine.IO options
  14. pingInterval: 10000,
  15. pingTimeout: 5000,
  16. cookie: false,
  17. });
  18. server.listen(3000, { origins: "*" });
  19. this.io.on("connection", (socket) => {
  20. let user = socket.handshake.query
  21. this._users.push(user)
  22. const roomId = user['roomId']
  23. console.log(user)
  24. socket.join(roomId, () => {
  25. let roomsPerson = this._roomPerson.get(roomId) || []
  26. roomsPerson.push(user)
  27. this._roomPerson.set(roomId, roomsPerson)
  28. // 只派发非小程序端的socket连接数及其user数据
  29. this.io.to(roomId).emit('vr_request', { persons: roomsPerson.filter(item => !item.isClient) });
  30. });
  31. socket.on('startCall', () => {
  32. socket.broadcast.to(roomId).emit('answer', { user })
  33. })
  34. socket.on('stopCall', () => {
  35. socket.broadcast.to(roomId).emit('putup', { user })
  36. })
  37. socket.on("getJson", (data) => {
  38. if (roomId) {
  39. this.io.to(roomId).emit("action", data.content.action);
  40. this.io.to(roomId).emit("vr_response", data);
  41. }
  42. });
  43. console.log("WebSocket服务端建立完毕");
  44. socket.on("disconnect", (reason) => {
  45. let roomsPerson = this._roomPerson.get(roomId) || []
  46. // 断开连接的把roomsPerson中的user去掉
  47. roomsPerson = roomsPerson.filter(item => item !== user)
  48. this._roomPerson.set(roomId, roomsPerson)
  49. this.io.to(roomId).emit('vr_request', { persons: roomsPerson.filter(item => !item.isClient) });
  50. console.log("关闭连接", reason);
  51. });
  52. socket.on("error", function (reason) {
  53. console.log("异常关闭", reason)
  54. });
  55. return this;
  56. })
  57. }
  58. close() {
  59. this.server.disconnect(true);
  60. }
  61. };