JsEnv.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 30s");
  21. setTimeout(function () {
  22. _this.connect()
  23. }, 30000)
  24. }
  25. this.socket["ySocket"].onclose = function () {
  26. console.log("connection failed,reconnect after 30s");
  27. setTimeout(function () {
  28. _this.connect()
  29. }, 30000)
  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.sendFailed(seq, 'need request param {action}');
  51. return
  52. }
  53. action=result["action"]
  54. var theHandler = this.handlers[action];
  55. try {
  56. if (!result["param"]){
  57. theHandler(function (response) {
  58. _this.sendResult(action, response);
  59. })
  60. }else{
  61. theHandler(function (response) {
  62. _this.sendResult(action, response);
  63. },result["param"])
  64. }
  65. } catch (e) {
  66. console.log("error: " + e);
  67. _this.sendResult(action+e);
  68. }
  69. }
  70. Hlclient.prototype.sendResult = function (action, e) {
  71. this.send(action + atob("aGxeX14") + e);
  72. }