WsController.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. "use strict";
  2. class WsController {
  3. constructor(ws, wss) {
  4. this.ws = ws;
  5. this.wss = wss;
  6. this.codeMap = require('../conf/code.inc.js');
  7. }
  8. actionBroadcast(args) {
  9. let text = args.text;
  10. // Broadcast to everyone else.
  11. var wss = this.wss;
  12. wss.clients.forEach(function each(client) {
  13. client.send(text);
  14. });
  15. }
  16. /**
  17. * sucess
  18. * @param {Array|String|Number} data 返回的数据
  19. * @param {String} msg 返回的msg
  20. * @param {String} debugMsg 调试的msg
  21. * @author benzhan
  22. */
  23. success(data, msg, debugMsg) {
  24. var code = CODE_SUCCESS;
  25. this.debugMsg = debugMsg;
  26. msg = msg || this.codeMap[code];
  27. if (global['DEBUG'] && debugMsg) {
  28. msg = msg + " 【调试信息:" + debugMsg + "】";
  29. }
  30. var ret = {
  31. result: 1,
  32. code: code,
  33. msg: msg,
  34. data: data
  35. };
  36. this.exitData(ret);
  37. }
  38. /**
  39. * error with code
  40. * @param {Number} code
  41. * @param {String} msg
  42. * @param {String} debugMsg
  43. * @param {String} extData
  44. * @author benzhan
  45. */
  46. error(code, msg, debugMsg, extData) {
  47. this.debugMsg = debugMsg;
  48. msg = msg || this.codeMap[code];
  49. if (global['DEBUG'] && debugMsg) {
  50. msg = msg + " 【调试信息:" + debugMsg + "】";
  51. }
  52. var ret = {
  53. result: 0,
  54. code: code,
  55. msg: msg
  56. };
  57. if (extData) {
  58. ret['data'] = extData;
  59. }
  60. this.exitData(ret);
  61. }
  62. exitData(ret) {
  63. var json = JSON.stringify(ret);
  64. this.exitMsg(json, ret['code']);
  65. }
  66. exitMsg(content, code) {
  67. var ws = this.ws;
  68. code = code || CODE_SUCCESS;
  69. //必须是字符串
  70. if (typeof content != "string") {
  71. content = JSON.stringify(content);
  72. }
  73. // 记录访问日志
  74. var objCallLog = new CallLog(this);
  75. objCallLog.logSelfCall(code, content);
  76. ws.send(content);
  77. }
  78. }
  79. module.exports = WsController;