index.js 2.6 KB

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