index.js 2.4 KB

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