├── .gitignore ├── .npmignore ├── LICENSE.txt ├── README.md ├── angular2-websocket.d.ts ├── package.json ├── src └── angular2-websocket.ts ├── tsconfig.json ├── tslint.json └── typings.json /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | node_modules/ 3 | npm-debug.log 4 | 5 | # compiled output 6 | typings/ 7 | angular2-websocket.js 8 | angular2-websocket.js.map 9 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .idea 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # angular2websocket 2 | 3 | Based on https://github.com/AngularClass/angular-websocket and migrated to Angular2 4 | ## Installation 5 | 6 | ```bash 7 | npm install angular2-websocket 8 | ``` 9 | 10 | ## Usage: 11 | ```ts 12 | import {$WebSocket} from 'angular2-websocket/angular2-websocket' 13 | var ws = new $WebSocket("url"); 14 | ws.send(event); 15 | 16 | ``` 17 | 18 | also 19 | ws.getDataStream() returns Subject to which you can attach an Observer (https://github.com/Reactive-Extensions/RxJS) 20 | 21 | ## Compilation 22 | ```bash 23 | npm run typings 24 | npm run compile 25 | 26 | ``` 27 | 28 | 29 | The default value for binary type is 'arrayBuffer'. 30 | 31 | ## example 32 | ```ts 33 | import {$WebSocket, WebSocketSendMode} from 'angular2-websocket/angular2-websocket'; 34 | 35 | // connect 36 | var ws = new $WebSocket("ws://127.0.0.1:7000"); 37 | // you can send immediately after connect, 38 | // data will cached until connect open and immediately send or connect fail. 39 | 40 | // when connect fail, websocket will reconnect or not, 41 | // you can set {WebSocketConfig.reconnectIfNotNormalClose = true} to enable auto reconnect 42 | // all cached data will lost when connect close if not reconnect 43 | 44 | 45 | // set received message callback 46 | ws.onMessage( 47 | (msg: MessageEvent)=> { 48 | console.log("onMessage ", msg.data); 49 | }, 50 | {autoApply: false} 51 | ); 52 | 53 | // set received message stream 54 | ws.getDataStream().subscribe( 55 | (msg)=> { 56 | console.log("next", msg.data); 57 | ws.close(false); 58 | }, 59 | (msg)=> { 60 | console.log("error", msg); 61 | }, 62 | ()=> { 63 | console.log("complete"); 64 | } 65 | ); 66 | 67 | // send with default send mode (now default send mode is Observer) 68 | ws.send("some thing").subscribe( 69 | (msg)=> { 70 | console.log("next", msg.data); 71 | }, 72 | (msg)=> { 73 | console.log("error", msg); 74 | }, 75 | ()=> { 76 | console.log("complete"); 77 | } 78 | ); 79 | 80 | ws.send("by default, this will never be sent, because Observer is cold."); 81 | ws.send("by default, this will be sent, because Observer is hot.").publish().connect(); 82 | 83 | ws.setSendMode(WebSocketSendMode.Direct); 84 | ws.send("this will be sent Direct, because send mode is set to Direct."); 85 | 86 | ws.send("this will be sent and return Promise.", WebSocketSendMode.Promise).then( 87 | (T) => { 88 | console.log("is send"); 89 | }, 90 | (T) => { 91 | console.log("not send"); 92 | } 93 | ); 94 | 95 | ws.send("this will be sent and return Observer.").subscribe( 96 | (msg)=> { 97 | console.log("next", msg.data); 98 | }, 99 | (msg)=> { 100 | console.log("error", msg); 101 | }, 102 | ()=> { 103 | console.log("complete"); 104 | } 105 | ); 106 | 107 | ws.close(false); // close 108 | ws.close(true); // close immediately 109 | 110 | 111 | ``` 112 | 113 | ## Binary type 114 | To set the binary type for the websocket one can provide it as string in the constructor. Allowed types are: 115 | 116 | * 'blob' (default) 117 | * 'arraybuffer' 118 | 119 | ```ts 120 | var ws = new $WebSocket("ws://127.0.0.1:7000", null, null, 'arraybuffer'); 121 | ``` -------------------------------------------------------------------------------- /angular2-websocket.d.ts: -------------------------------------------------------------------------------- 1 | import { Observable, Subject } from 'rxjs'; 2 | export declare class $WebSocket { 3 | private url; 4 | private protocols; 5 | private config; 6 | private binaryType; 7 | private static Helpers; 8 | private reconnectAttempts; 9 | private sendQueue; 10 | private onOpenCallbacks; 11 | private onMessageCallbacks; 12 | private onErrorCallbacks; 13 | private onCloseCallbacks; 14 | private readyStateConstants; 15 | private normalCloseCode; 16 | private reconnectableStatusCodes; 17 | private socket; 18 | private dataStream; 19 | private errorMessages; 20 | private internalConnectionState; 21 | constructor(url: string, protocols?: Array, config?: WebSocketConfig, binaryType?: BinaryType); 22 | connect(force?: boolean): void; 23 | getErrorStream(): Subject; 24 | /** 25 | * Run in Block Mode 26 | * Return true when can send and false in socket closed 27 | * @param data 28 | * @returns {boolean} 29 | */ 30 | send4Direct(data: any, binary?: boolean): boolean; 31 | /** 32 | * Return Promise 33 | * When can Send will resolve Promise 34 | * When Socket closed will reject Promise 35 | * @param data 36 | * @returns {Promise} 37 | */ 38 | send4Promise(data: any, binary?: boolean): Promise; 39 | /** 40 | * Return cold Observable 41 | * When can Send will complete observer 42 | * When Socket closed will error observer 43 | * @param data 44 | * @returns {Observable} 45 | */ 46 | send4Observable(data: any, binary?: boolean): Observable; 47 | private send4Mode; 48 | /** 49 | * Set send(data) function return mode 50 | * @param mode 51 | */ 52 | setSend4Mode(mode: WebSocketSendMode): void; 53 | /** 54 | * Use {mode} mode to send {data} data 55 | * If no specify, Default SendMode is Observable mode 56 | * @param data 57 | * @param mode 58 | * @param binary 59 | * @returns {any} 60 | */ 61 | send(data: any, mode?: WebSocketSendMode, binary?: boolean): any; 62 | getDataStream(): Subject; 63 | onOpenHandler(event: Event): void; 64 | notifyOpenCallbacks(event: any): void; 65 | fireQueue(): void; 66 | notifyCloseCallbacks(event: any): void; 67 | notifyErrorCallbacks(event: any): void; 68 | onOpen(cb: any): this; 69 | onClose(cb: any): this; 70 | onError(cb: any): this; 71 | onMessage(callback: any, options?: any): this; 72 | onMessageHandler(message: MessageEvent): void; 73 | onCloseHandler(event: CloseEvent): void; 74 | onErrorHandler(event: any): void; 75 | reconnect(): this; 76 | close(force?: boolean, keepReconnectIfNotNormalClose?: boolean): this; 77 | getBackoffDelay(attempt: any): number; 78 | setInternalState(state: any): void; 79 | /** 80 | * Could be -1 if not initzialized yet 81 | * @returns {number} 82 | */ 83 | getReadyState(): number; 84 | } 85 | export interface WebSocketConfig { 86 | initialTimeout?: number; 87 | maxTimeout?: number; 88 | reconnectIfNotNormalClose?: boolean; 89 | } 90 | export declare enum WebSocketSendMode { 91 | Direct = 0, 92 | Promise = 1, 93 | Observable = 2, 94 | } 95 | export declare type BinaryType = "blob" | "arraybuffer"; 96 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular2-websocket", 3 | "main": "angular2-websocket", 4 | "version": "0.9.8", 5 | "license": "MIT", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "compile": "tsc", 9 | "typings": "typings install", 10 | "lint": "tslint \"src/**/*.ts\"", 11 | "compile-no-dts": "tsc --declaration false" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/afrad/angular2-websocket.git" 16 | }, 17 | "dependencies": { 18 | "bluebird": "^3.4.6" 19 | }, 20 | "peerDependencies": { 21 | "core-js": "^2.5.0", 22 | "reflect-metadata": "^0.1.8", 23 | "typescript": "^3.2.0", 24 | "zone.js": "^0.8.12" 25 | }, 26 | "devDependencies": { 27 | "@angular/common": "^7.0.0", 28 | "@angular/compiler": "^7.0.0", 29 | "@angular/core": "^7.0.0", 30 | "@types/bluebird": "^3.0.35", 31 | "codelyzer": "^4.3.0", 32 | "core-js": "^2.5.0", 33 | "grunt": "~0.4.1", 34 | "grunt-contrib-uglify": "~0.2.4", 35 | "grunt-typescript": "~0.2.4", 36 | "reflect-metadata": "^0.1.8", 37 | "rxjs": "^6.1.0", 38 | "tslint": "~5.7.0", 39 | "typescript": "^3.2.0", 40 | "typings": "^2.0.0", 41 | "zone.js": "^0.8.12" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/angular2-websocket.ts: -------------------------------------------------------------------------------- 1 | import {Injectable} from '@angular/core'; 2 | import {Observable, Subject} from 'rxjs'; 3 | 4 | export class $WebSocket { 5 | 6 | private static Helpers = class { 7 | static isPresent(obj: any): boolean { 8 | return obj !== undefined && obj !== null; 9 | } 10 | 11 | static isString(obj: any): boolean { 12 | return typeof obj === 'string'; 13 | } 14 | 15 | static isArray(obj: any): boolean { 16 | return Array.isArray(obj); 17 | } 18 | 19 | static isFunction(obj: any): boolean { 20 | return typeof obj === 'function'; 21 | } 22 | }; 23 | 24 | private reconnectAttempts = 0; 25 | private sendQueue = []; 26 | private onOpenCallbacks = []; 27 | private onMessageCallbacks = []; 28 | private onErrorCallbacks = []; 29 | private onCloseCallbacks = []; 30 | private readyStateConstants = { 31 | 'UNINITIALIZED': -1, 32 | 'CONNECTING': 0, 33 | 'OPEN': 1, 34 | 'CLOSING': 2, 35 | 'CLOSED': 3, 36 | 'RECONNECT_ABORTED': 4 37 | }; 38 | private normalCloseCode = 1000; 39 | private reconnectableStatusCodes = [4000]; 40 | private socket: WebSocket; 41 | private dataStream: Subject; 42 | private errorMessages: Subject; 43 | private internalConnectionState: number; 44 | 45 | constructor(private url: string, 46 | private protocols?: Array, 47 | private config?: WebSocketConfig, 48 | private binaryType?: BinaryType) 49 | { 50 | let match = new RegExp('wss?:\/\/').test(url); 51 | if (!match) { 52 | throw new Error('Invalid url provided'); 53 | } 54 | this.config = Object.assign({ initialTimeout: 500, maxTimeout: 300000, reconnectIfNotNormalClose: false }, config); 55 | this.binaryType = binaryType || 'blob'; 56 | this.dataStream = new Subject(); 57 | this.errorMessages = new Subject(); 58 | this.connect(true); 59 | } 60 | 61 | connect(force = false) { 62 | // console.log("WebSocket connecting..."); 63 | let self = this; 64 | if (force || !this.socket || this.socket.readyState !== this.readyStateConstants.OPEN) { 65 | self.socket = this.protocols ? new WebSocket(this.url, this.protocols) : new WebSocket(this.url); 66 | self.socket.binaryType = self.binaryType; 67 | 68 | self.socket.onopen = (ev: Event) => { 69 | // console.log('onOpen: ', ev); 70 | this.onOpenHandler(ev); 71 | }; 72 | self.socket.onmessage = (ev: MessageEvent) => { 73 | // console.log('onNext: ', ev.data); 74 | self.onMessageHandler(ev); 75 | this.dataStream.next(ev); 76 | }; 77 | this.socket.onclose = (ev: CloseEvent) => { 78 | // console.log('onClose ', ev); 79 | self.onCloseHandler(ev); 80 | }; 81 | 82 | this.socket.onerror = (ev: ErrorEvent) => { 83 | // console.log('onError ', ev); 84 | self.onErrorHandler(ev); 85 | this.errorMessages.next(ev); 86 | }; 87 | 88 | } 89 | } 90 | 91 | getErrorStream(): Subject { 92 | return this.errorMessages; 93 | } 94 | 95 | /** 96 | * Run in Block Mode 97 | * Return true when can send and false in socket closed 98 | * @param data 99 | * @returns {boolean} 100 | */ 101 | send4Direct(data, binary?: boolean): boolean { 102 | let self = this; 103 | if (this.getReadyState() !== this.readyStateConstants.OPEN 104 | && this.getReadyState() !== this.readyStateConstants.CONNECTING) { 105 | this.connect(); 106 | } 107 | self.sendQueue.push({message: data, binary: binary}); 108 | if (self.socket.readyState === self.readyStateConstants.OPEN) { 109 | self.fireQueue(); 110 | return true; 111 | } else { 112 | return false; 113 | } 114 | } 115 | 116 | /** 117 | * Return Promise 118 | * When can Send will resolve Promise 119 | * When Socket closed will reject Promise 120 | * @param data 121 | * @returns {Promise} 122 | */ 123 | send4Promise(data, binary?: boolean): Promise { 124 | return new Promise( 125 | (resolve, reject) => { 126 | if (this.send4Direct(data, binary)) { 127 | return resolve(); 128 | } else { 129 | return reject(Error('Socket connection has been closed')); 130 | } 131 | } 132 | ) 133 | } 134 | 135 | /** 136 | * Return cold Observable 137 | * When can Send will complete observer 138 | * When Socket closed will error observer 139 | * @param data 140 | * @returns {Observable} 141 | */ 142 | send4Observable(data, binary?: boolean): Observable { 143 | return Observable.create((observer) => { 144 | if (this.send4Direct(data, binary)) { 145 | return observer.complete(); 146 | } else { 147 | return observer.error('Socket connection has been closed'); 148 | } 149 | }); 150 | } 151 | 152 | private send4Mode: WebSocketSendMode = WebSocketSendMode.Observable; 153 | 154 | /** 155 | * Set send(data) function return mode 156 | * @param mode 157 | */ 158 | setSend4Mode(mode: WebSocketSendMode): void { 159 | this.send4Mode = mode; 160 | } 161 | 162 | /** 163 | * Use {mode} mode to send {data} data 164 | * If no specify, Default SendMode is Observable mode 165 | * @param data 166 | * @param mode 167 | * @param binary 168 | * @returns {any} 169 | */ 170 | send(data: any, mode?: WebSocketSendMode, binary?: boolean): any { 171 | switch (typeof mode !== 'undefined' ? mode : this.send4Mode) { 172 | case WebSocketSendMode.Direct: 173 | return this.send4Direct(data, binary); 174 | case WebSocketSendMode.Promise: 175 | return this.send4Promise(data, binary); 176 | case WebSocketSendMode.Observable: 177 | return this.send4Observable(data, binary); 178 | default: 179 | throw Error('WebSocketSendMode Error.'); 180 | } 181 | } 182 | 183 | getDataStream(): Subject { 184 | return this.dataStream; 185 | } 186 | 187 | onOpenHandler(event: Event) { 188 | this.reconnectAttempts = 0; 189 | this.notifyOpenCallbacks(event); 190 | this.fireQueue(); 191 | } 192 | 193 | notifyOpenCallbacks(event) { 194 | for (let i = 0; i < this.onOpenCallbacks.length; i++) { 195 | this.onOpenCallbacks[i].call(this, event); 196 | } 197 | } 198 | 199 | fireQueue() { 200 | // console.log("fireQueue()"); 201 | while (this.sendQueue.length && this.socket.readyState === this.readyStateConstants.OPEN) { 202 | let data = this.sendQueue.shift(); 203 | 204 | // console.log("fireQueue: ", data); 205 | if (data.binary) { 206 | this.socket.send(data.message); 207 | } else { 208 | this.socket.send( 209 | $WebSocket.Helpers.isString(data.message) ? data.message : JSON.stringify(data.message) 210 | ); 211 | } 212 | // data.deferred.resolve(); 213 | } 214 | } 215 | 216 | notifyCloseCallbacks(event) { 217 | for (let i = 0; i < this.onCloseCallbacks.length; i++) { 218 | this.onCloseCallbacks[i].call(this, event); 219 | } 220 | } 221 | 222 | notifyErrorCallbacks(event) { 223 | for (let i = 0; i < this.onErrorCallbacks.length; i++) { 224 | this.onErrorCallbacks[i].call(this, event); 225 | } 226 | } 227 | 228 | onOpen(cb) { 229 | this.onOpenCallbacks.push(cb); 230 | return this; 231 | }; 232 | 233 | onClose(cb) { 234 | this.onCloseCallbacks.push(cb); 235 | return this; 236 | } 237 | 238 | onError(cb) { 239 | this.onErrorCallbacks.push(cb); 240 | return this; 241 | }; 242 | 243 | onMessage(callback, options?) { 244 | if (!$WebSocket.Helpers.isFunction(callback)) { 245 | throw new Error('Callback must be a function'); 246 | } 247 | 248 | this.onMessageCallbacks.push({ 249 | fn: callback, 250 | pattern: options ? options.filter : undefined, 251 | autoApply: options ? options.autoApply : true 252 | }); 253 | return this; 254 | } 255 | 256 | onMessageHandler(message: MessageEvent) { 257 | let self = this; 258 | let currentCallback; 259 | for (let i = 0; i < self.onMessageCallbacks.length; i++) { 260 | currentCallback = self.onMessageCallbacks[i]; 261 | currentCallback.fn.apply(self, [message]); 262 | } 263 | }; 264 | 265 | onCloseHandler(event: CloseEvent) { 266 | this.notifyCloseCallbacks(event); 267 | if ((this.config.reconnectIfNotNormalClose && event.code !== this.normalCloseCode) 268 | || this.reconnectableStatusCodes.indexOf(event.code) > -1) { 269 | this.reconnect(); 270 | } else { 271 | this.sendQueue = []; 272 | this.dataStream.complete(); 273 | } 274 | }; 275 | 276 | onErrorHandler(event) { 277 | this.notifyErrorCallbacks(event); 278 | }; 279 | 280 | reconnect() { 281 | this.close(true, true); 282 | let backoffDelay = this.getBackoffDelay(++this.reconnectAttempts); 283 | // let backoffDelaySeconds = backoffDelay / 1000; 284 | // console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); 285 | setTimeout(() => { 286 | if (this.config.reconnectIfNotNormalClose) { 287 | this.connect() 288 | } 289 | }, backoffDelay); 290 | return this; 291 | } 292 | 293 | close(force: boolean = false, keepReconnectIfNotNormalClose?: boolean) { 294 | if (!keepReconnectIfNotNormalClose) { 295 | this.config.reconnectIfNotNormalClose = false; 296 | } 297 | 298 | if (force || !this.socket.bufferedAmount) { 299 | this.socket.close(this.normalCloseCode); 300 | } 301 | return this; 302 | }; 303 | 304 | // Exponential Backoff Formula by Prof. Douglas Thain 305 | // http://dthain.blogspot.co.uk/2009/02/exponential-backoff-in-distributed.html 306 | getBackoffDelay(attempt) { 307 | let R = Math.random() + 1; 308 | let T = this.config.initialTimeout; 309 | let F = 2; 310 | let N = attempt; 311 | let M = this.config.maxTimeout; 312 | 313 | return Math.floor(Math.min(R * T * Math.pow(F, N), M)); 314 | }; 315 | 316 | setInternalState(state) { 317 | if (Math.floor(state) !== state || state < 0 || state > 4) { 318 | throw new Error('state must be an integer between 0 and 4, got: ' + state); 319 | } 320 | 321 | this.internalConnectionState = state; 322 | 323 | } 324 | 325 | getReadyState() { 326 | if (this.socket == null) { 327 | return this.readyStateConstants.UNINITIALIZED; 328 | } 329 | return this.internalConnectionState || this.socket.readyState; 330 | } 331 | } 332 | 333 | export interface WebSocketConfig { 334 | initialTimeout?: number; 335 | maxTimeout?: number; 336 | reconnectIfNotNormalClose?: boolean; 337 | } 338 | 339 | export enum WebSocketSendMode { 340 | Direct, Promise, Observable 341 | } 342 | 343 | export type BinaryType = "blob" | "arraybuffer"; 344 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "sourceMap": true, 7 | "emitDecoratorMetadata": true, 8 | "experimentalDecorators": true, 9 | "removeComments": false, 10 | "outDir": "./", 11 | "declaration": true 12 | }, 13 | "exclude": [ 14 | "node_modules", 15 | "typings/main", 16 | "typings/main.d.ts" 17 | ] 18 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "class-name": true, 7 | "comment-format": [ 8 | true, 9 | "check-space" 10 | ], 11 | "curly": true, 12 | "eofline": true, 13 | "forin": true, 14 | "indent": [ 15 | true, 16 | "spaces" 17 | ], 18 | "label-position": true, 19 | "label-undefined": true, 20 | "max-line-length": [ 21 | true, 22 | 140 23 | ], 24 | "member-access": false, 25 | "member-ordering": [ 26 | true, 27 | { 28 | "order": "fields-first" 29 | } 30 | ], 31 | "no-arg": true, 32 | "no-bitwise": true, 33 | "no-console": [ 34 | true, 35 | "debug", 36 | "info", 37 | "time", 38 | "timeEnd", 39 | "trace" 40 | ], 41 | "no-construct": true, 42 | "no-debugger": true, 43 | "no-duplicate-key": true, 44 | "no-duplicate-variable": true, 45 | "no-empty": false, 46 | "no-eval": true, 47 | "no-inferrable-types": true, 48 | "no-shadowed-variable": true, 49 | "no-string-literal": false, 50 | "no-switch-case-fall-through": true, 51 | "no-trailing-whitespace": true, 52 | "no-unused-expression": true, 53 | "no-unused-variable": true, 54 | "no-unreachable": true, 55 | "no-use-before-declare": true, 56 | "no-var-keyword": true, 57 | "object-literal-sort-keys": false, 58 | "one-line": [ 59 | true, 60 | "check-open-brace", 61 | "check-catch", 62 | "check-else", 63 | "check-whitespace" 64 | ], 65 | "quotemark": [ 66 | true, 67 | "single" 68 | ], 69 | "radix": true, 70 | "semicolon": [ 71 | "always" 72 | ], 73 | "triple-equals": [ 74 | true, 75 | "allow-null-check" 76 | ], 77 | "typedef-whitespace": [ 78 | true, 79 | { 80 | "call-signature": "nospace", 81 | "index-signature": "nospace", 82 | "parameter": "nospace", 83 | "property-declaration": "nospace", 84 | "variable-declaration": "nospace" 85 | } 86 | ], 87 | "variable-name": false, 88 | "whitespace": [ 89 | true, 90 | "check-branch", 91 | "check-decl", 92 | "check-operator", 93 | "check-separator", 94 | "check-type" 95 | ], 96 | "directive-selector-name": [ 97 | true, 98 | "camelCase" 99 | ], 100 | "component-selector-name": [ 101 | true, 102 | "kebab-case" 103 | ], 104 | "directive-selector-type": [ 105 | true, 106 | "attribute" 107 | ], 108 | "component-selector-type": [ 109 | true, 110 | "element" 111 | ], 112 | "use-input-property-decorator": true, 113 | "use-output-property-decorator": true, 114 | "use-host-property-decorator": true, 115 | "no-input-rename": true, 116 | "no-output-rename": true, 117 | "use-life-cycle-interface": true, 118 | "use-pipe-transform-interface": true, 119 | "component-class-suffix": true, 120 | "directive-class-suffix": true 121 | } 122 | } -------------------------------------------------------------------------------- /typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "globalDependencies": { 3 | "core-js": "registry:dt/core-js#0.0.0+20160914114559" 4 | } 5 | } 6 | --------------------------------------------------------------------------------