JsEnv.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. return true
  45. }
  46. //收到消息后这里处理,
  47. Hlclient.prototype.handlerRequest = function (requestJson) {
  48. var _this = this;
  49. var result=JSON.parse(requestJson);
  50. //console.log(result)
  51. if (!result['action']) {
  52. this.sendResult('','need request param {action}');
  53. return
  54. }
  55. var action=result["action"]
  56. var theHandler = this.handlers[action];
  57. if (!theHandler){
  58. this.sendResult(action,'action not found');
  59. return
  60. }
  61. try {
  62. if (!result["param"]){
  63. theHandler(function (response) {
  64. _this.sendResult(action, response);
  65. })
  66. }else{
  67. try {
  68. result["param"]=JSON.parse(result["param"])
  69. }catch (e){
  70. console.log("")
  71. }
  72. theHandler(function (response) {
  73. _this.sendResult(action, response);
  74. },result["param"])
  75. }
  76. } catch (e) {
  77. console.log("error: " + e);
  78. _this.sendResult(action+e);
  79. }
  80. }
  81. Hlclient.prototype.sendResult = function (action, e) {
  82. this.send(action + atob("aGxeX14") + e);
  83. }