index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. var server = require("http").createServer();
  2. module.exports = class WebSocketServer {
  3. constructor() {
  4. this.connMap = new Map();
  5. this._pageMap = new Map();
  6. this._count = 0;
  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. this._count = this._count >= this._users.length ? 0 : this._count;
  21. let user = socket.handshake.query
  22. this._users.push(user)
  23. let userId = user.role === 'customer' ? 'customerId' : 'agentId'
  24. let friendId = user.role !== 'customer' ? 'customerId' : 'agentId'
  25. this.connMap.set(userId, socket);
  26. socket.emit('vr_request', { userInfo: user });
  27. this._count++;
  28. socket.on("getJson", (data) => {
  29. console.log("收到的信息为:" + data);
  30. let msg = data;
  31. let connTemp = this.connMap.get(friendId);
  32. let action = msg.content.action
  33. socket.emit("action", action,()=>{
  34. console.log(action)
  35. });
  36. !!connTemp && this.sendText(connTemp, msg, (msgSendFinally) => {
  37. console.log(msgSendFinally)
  38. });
  39. });
  40. console.log("WebSocket服务端建立完毕");
  41. socket.on("disconnect", function (reason) {
  42. // this.connMap[userId] && (delete this.connMap[userId])
  43. // console.log(this.connMap)
  44. console.log("关闭连接", reason);
  45. });
  46. socket.on("error", function (reason) {
  47. console.log("异常关闭", reason)
  48. });
  49. return this;
  50. });
  51. }
  52. close() {
  53. this.server.disconnect(true);
  54. }
  55. sendText(socket, msg, cbOk) {
  56. const msgSendFinally = msg;
  57. let action = msg.content.action
  58. socket.emit("action", action,()=>{
  59. console.log(action)
  60. });
  61. socket.emit("vr_response", msgSendFinally,()=>{
  62. cbOk && cbOk(msgSendFinally);
  63. });
  64. }
  65. };