websocketClient.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //参考https://github.com/MacArthurJustin/vue-remote 修改
  2. /**
  3. *var client=WsClient({host:"127.0.0.1",port:9502});
  4. *client.connect();//链接服务器
  5. *client.on('/index/index/index',function(data){console.log(data)}).emit('/index/index/index',"data")//on每次绑定都不会销毁
  6. *client.once('/index/index/index',function(data){console.log(data)}).emit('/index/index/index',"data")//once每次绑定,接收数据后就销毁当前接收方法
  7. */
  8. (function webpackUniversalModuleDefinition(root, factory) {
  9. if (typeof exports === 'object' && typeof module === 'object')
  10. module.exports = factory();
  11. else if (typeof define === 'function' && define.amd)
  12. define([], factory);
  13. else if (typeof exports === 'object')
  14. exports["WsClient"] = factory();
  15. else
  16. root["WsClient"] = factory();
  17. })(this, function () {
  18. var WsClient = function (options) {
  19. var Client = null,
  20. Handlers = Object.create(null),
  21. socketPump = [],
  22. pumpInterval = null;
  23. options = options || {};
  24. options.secure = options.secure || false;
  25. options.host = options.host || "localhost";
  26. options.port = options.port || 8080;
  27. options.identifier = options.identifier || 'event';
  28. options.endpoint = options.endpoint || '';
  29. options.camelCase = options.camelCase || true;
  30. /**
  31. * Connect to Websocket Server
  32. */
  33. function connect() {
  34. Client = new WebSocket(`${(options.secure ? 'wss://' : 'ws://')}${options.host}${options.port ? ':' + options.port : ''}/${options.endpoint}`, options.protocol);
  35. Client.onopen = openHandler;
  36. Client.onerror = errorHandler;
  37. Client.onmessage = messageHandler;
  38. Client.onclose = closeHandler
  39. }
  40. /**
  41. * Handle Server Connection Event
  42. *
  43. * @param {Event} open
  44. */
  45. function openHandler(open) {
  46. console.log("Connected to Web Server");
  47. console.log(open);
  48. if (options.openHandler) options.openHandler(open)
  49. }
  50. /**
  51. * Handle Server Errors
  52. *
  53. * @param {Event} error
  54. */
  55. function errorHandler(error) {
  56. console.log("Error occured");
  57. console.log(error);
  58. if (options.errorHandler) options.errorHandler(error)
  59. }
  60. /**
  61. * Handle Messages Returned from the Server
  62. *
  63. * @param {MessageEvent} message
  64. * @returns
  65. */
  66. function messageHandler(message) {
  67. var Json = JSON.parse(message.data),
  68. identifier = options.camelCase ? Json[options.identifier].replace(
  69. /-([A-Za-z0-9])/gi,
  70. (s, group1) => group1.toUpperCase()
  71. ) : Json[options.identifier],
  72. Events = Handlers[identifier];
  73. if (Events) {
  74. Events.forEach(
  75. (Event) => {
  76. //Event.callback.apply(Event.thisArg, [Json.data])
  77. //Adapt to all respone format
  78. Event.callback.apply(Event.thisArg, [Json])
  79. }
  80. )
  81. }
  82. }
  83. /**
  84. * {EventListener} For When the Websocket Client Closes the Connection
  85. *
  86. * @param {CloseEvent} close
  87. */
  88. function closeHandler(close) {
  89. if (options.closeHandler) options.closeHandler(close);
  90. if (pumpInterval) {
  91. window.clearInterval(pumpInterval);
  92. pumpInterval = null
  93. }
  94. Client = null
  95. }
  96. /**
  97. * Attaches Handlers to the Event Pump System
  98. *
  99. * @param {Boolean} server True/False whether the Server should process the trigger
  100. * @param {String} identifier Unique Name of the trigger
  101. * @param {Function} callback Function to be called when the trigger is tripped
  102. * @param {Object} [thisArg] Arguement to be passed to the handler as `this`
  103. */
  104. function attachHandler(identifier, callback, thisArg) {
  105. identifier = options.camelCase ? identifier.replace(
  106. /-([A-Za-z0-9])/gi,
  107. (s, group1) => group1.toUpperCase()
  108. ) : identifier;
  109. !(Handlers[identifier] || (Handlers[identifier] = [])).push({
  110. callback: callback,
  111. thisArg: thisArg
  112. })
  113. }
  114. /**
  115. * Detaches Handlers from the Event Pump System
  116. *
  117. * @param {String} identifier Unique Name of the trigger
  118. * @param {Function} callback Function to be called when the trigger is tripped
  119. */
  120. function detachHandler(identifier, callback) {
  121. if (arguments.length === 0) {
  122. Handlers = Object.create(null);
  123. return
  124. }
  125. var Handler = Handlers[identifier];
  126. if (!Handler) return;
  127. if (arguments.length === 1) {
  128. Handlers[identifier] = null;
  129. return
  130. }
  131. for (var index = Handler.length - 1; index >= 0; index--) {
  132. if (Handler[index].callback === callback || Handler[index].callback.fn === callback) {
  133. Handler.splice(index, 1)
  134. }
  135. }
  136. }
  137. /**
  138. * Handles Event Triggers
  139. *
  140. * @param {String} identifier
  141. * @returns
  142. */
  143. function emitUrlHandler(identifier) {
  144. var url = arguments[1] || '/';
  145. var args = arguments[2] || [];
  146. if (arguments.length > 3) {
  147. args = arguments.length > 1 ? [].slice.apply(arguments, [1]) : []
  148. }
  149. if (typeof args === "object") {
  150. args.identifier = identifier;
  151. socketPump.push(JSON.stringify(args));
  152. return
  153. }
  154. socketPump.push(
  155. JSON.stringify({
  156. "event": identifier,
  157. "url": url,
  158. 'arguments': args
  159. })
  160. )
  161. }
  162. function emitHandler(identifier) {
  163. console.log(arguments);
  164. var args = arguments[1] || [];
  165. if (arguments.length > 2) {
  166. args = arguments.length > 1 ? [].slice.apply(arguments, [1]) : []
  167. }
  168. if (typeof args === "object") {
  169. args.identifier = identifier;
  170. socketPump.push(JSON.stringify(args));
  171. return
  172. }
  173. socketPump.push(
  174. JSON.stringify({
  175. "event": identifier,
  176. "url": identifier,
  177. 'arguments': args
  178. })
  179. )
  180. }
  181. /**
  182. * Sends Messages to the Websocket Server every 250 ms
  183. *
  184. * @returns
  185. */
  186. function pumpHandler() {
  187. if (socketPump.length === 0) return;
  188. if (!Client) connect();
  189. if (Client.readyState === WebSocket.OPEN) {
  190. socketPump.forEach(
  191. (item) => Client.send(item)
  192. );
  193. socketPump.length = 0
  194. }
  195. }
  196. if (!pumpInterval) window.setInterval(pumpHandler, 250);
  197. return {
  198. connect: connect,
  199. disconnect: function () {
  200. if (Client) {
  201. Client.close();
  202. Client = null
  203. }
  204. },
  205. attach: attachHandler,
  206. detach: detachHandler,
  207. emitUrl: emitUrlHandler,
  208. emit: emitHandler,
  209. on: function (identifier, callback) {
  210. this.attach(identifier, callback, this);
  211. return this
  212. },
  213. once: function (identifier, callback) {
  214. const thisArg = this;
  215. function once() {
  216. this.detach(identifier, callback);
  217. callback.apply(thisArg, arguments)
  218. }
  219. once.fn = callback;
  220. this.attach(identifier, once, thisArg);
  221. return thisArg
  222. },
  223. off: function (identifier, callback) {
  224. this.detach(identifier, callback, this);
  225. return this
  226. }
  227. }
  228. };
  229. return WsClient;
  230. });