JsEnv.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. function Hlclient(wsURL) {
  2. this.wsURL = wsURL;
  3. this.handlers = {};
  4. this.socket = {};
  5. if (!wsURL) {
  6. throw new Error('wsURL can not be empty!!')
  7. }
  8. this.connect()
  9. }
  10. Hlclient.prototype.connect = function () {
  11. console.log('begin of connect to wsURL: ' + this.wsURL);
  12. var _this = this;
  13. try {
  14. this.socket["ySocket"] = new WebSocket(this.wsURL);
  15. this.socket["ySocket"].onmessage = function (e) {
  16. console.log("send func", e.data);
  17. _this.handlerRequest(e.data);
  18. }
  19. } catch (e) {
  20. console.log("connection failed,reconnect after 10s");
  21. setTimeout(function () {
  22. _this.connect()
  23. }, 10000)
  24. }
  25. this.socket["ySocket"].onclose = function () {
  26. console.log("connection failed,reconnect after 10s");
  27. setTimeout(function () {
  28. _this.connect()
  29. }, 10000)
  30. }
  31. };
  32. Hlclient.prototype.send = function (msg) {
  33. this.socket["ySocket"].send(msg)
  34. }
  35. Hlclient.prototype.regAction = function (func_name, func) {
  36. if (typeof func_name !== 'string') {
  37. throw new Error("an func_name must be string");
  38. }
  39. if (typeof func !== 'function') {
  40. throw new Error("must be function");
  41. }
  42. console.log("register func_name: " + func_name);
  43. this.handlers[func_name] = func;
  44. }
  45. Hlclient.prototype.handlerRequest = function (requestJson) {
  46. var _this = this;
  47. var result=JSON.parse(requestJson);
  48. //console.log(result)
  49. if (!result['action']) {
  50. this.sendResult('','need request param {action}');
  51. return
  52. }
  53. action=result["action"]
  54. var theHandler = this.handlers[action];
  55. if (!theHandler ||theHandler==undefined){
  56. this.sendResult(action,'action not found');
  57. return
  58. }
  59. try {
  60. if (!result["param"]){
  61. theHandler(function (response) {
  62. _this.sendResult(action, response);
  63. })
  64. }else{
  65. theHandler(function (response) {
  66. _this.sendResult(action, response);
  67. },result["param"])
  68. }
  69. } catch (e) {
  70. console.log("error: " + e);
  71. _this.sendResult(action+e);
  72. }
  73. }
  74. Hlclient.prototype.sendResult = function (action, e) {
  75. this.send(action + atob("aGxeX14") + e);
  76. }