app.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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: "/vr-node",
  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. if (!user[isClient]) {
  30. this.io.to(roomId).emit('vr_request', { persons: roomsPerson.filter(item => !item.isClient) });
  31. }
  32. });
  33. socket.on('startCall', () => {
  34. socket.broadcast.to(roomId).emit('answer', { user })
  35. })
  36. socket.on('stopCall', () => {
  37. socket.broadcast.to(roomId).emit('putup', { user })
  38. })
  39. socket.on("getJson", (data) => {
  40. if (roomId) {
  41. this.io.to(roomId).emit("action", data.content.action);
  42. this.io.to(roomId).emit("vr_response", data);
  43. }
  44. });
  45. console.log("WebSocket服务端建立完毕");
  46. socket.on("disconnect", (reason) => {
  47. let roomsPerson = this._roomPerson.get(roomId) || []
  48. // 断开连接的把roomsPerson中的user去掉
  49. roomsPerson = roomsPerson.filter(item => item !== user)
  50. this._roomPerson.set(roomId, roomsPerson)
  51. if (!user.isClient) {
  52. this.io.to(roomId).emit('vr_request', { persons: roomsPerson.filter(item => !item.isClient) });
  53. console.log("关闭连接", reason);
  54. }
  55. });
  56. socket.on("error", function (reason) {
  57. console.log("异常关闭", reason)
  58. });
  59. return this;
  60. })
  61. }
  62. close() {
  63. this.server.disconnect(true);
  64. }
  65. };