@@ -7,23 +7,30 @@ export default class Client extends EventEmitter {
77 * @param {WebSocket } socket
88 * @param {String } ip
99 * @param {Encoder } encoder
10+ * @param {Number } pingFrequency Ping frequency in milliseconds
1011 */
11- constructor ( socket , ip , encoder ) {
12+ constructor ( socket , ip , encoder , pingFrequency = 0 ) {
1213 super ( ) ;
1314
14- this . socket = socket ;
15+ this . id = ++ INDEX ;
1516 this . ip = ip ;
17+ this . socket = socket ;
1618 this . encoder = encoder ;
17- this . id = ++ INDEX ;
19+ this . pingInterval = null ;
1820
1921 this . onMessage = this . onMessage . bind ( this ) ;
2022 this . onError = this . onError . bind ( this ) ;
2123 this . onClose = this . onClose . bind ( this ) ;
24+ this . ping = this . ping . bind ( this ) ;
2225
2326 this . socket . on ( 'message' , this . onMessage ) ;
2427 this . socket . on ( 'error' , this . onError ) ;
2528 this . socket . on ( 'close' , this . onClose ) ;
2629
30+ if ( pingFrequency > 0 ) {
31+ this . socket . on ( 'open' , ( ) => this . startPing ( pingFrequency ) ) ;
32+ }
33+
2734 this . socket . send = this . encoder . constructor . binaryType === 'arraybuffer' ? this . socket . binary : this . socket . text ;
2835
2936 this . socket . start ( ) ;
@@ -48,15 +55,46 @@ export default class Client extends EventEmitter {
4855 }
4956 }
5057
58+ /**
59+ * Start ping at given interval
60+ *
61+ * @param {Number } frequency Ping frequency in milliseconds
62+ */
63+ startPing ( frequency ) {
64+ if ( frequency ) {
65+ this . pingInterval = setInterval ( this . ping , frequency ) ;
66+ }
67+ }
68+
69+ ping ( ) {
70+ if ( this . socket ) {
71+ this . socket . ping ( ) ;
72+ }
73+ }
74+
75+ /**
76+ * Stop ping interval
77+ */
78+ stopPing ( ) {
79+ if ( this . pingInterval ) {
80+ clearInterval ( this . pingInterval ) ;
81+ this . pingInterval = null ;
82+ }
83+ }
84+
5185 /**
5286 * On message
5387 *
5488 * @param {Event } event
5589 */
5690 onMessage ( event ) {
57- const { name, data } = this . encoder . decode ( event . data ) ;
91+ try {
92+ const { name, data } = this . encoder . decode ( event . data ) ;
5893
59- this . emit ( name , data , this ) ;
94+ this . emit ( name , data , this ) ;
95+ } catch ( error ) {
96+ console . error ( '[ERROR] Could not parse message:' , error , '\n\r\tEvent: ' , event ) ;
97+ }
6098 }
6199
62100 /**
@@ -66,12 +104,14 @@ export default class Client extends EventEmitter {
66104 */
67105 onError ( event ) {
68106 console . error ( `Client ${ this . id } : ` , event . message ) ;
107+ this . close ( ) ;
69108 }
70109
71110 /**
72111 * On close
73112 */
74113 onClose ( ) {
114+ this . stopPing ( ) ;
75115 this . socket = null ;
76116 this . emit ( 'close' , this ) ;
77117 }
0 commit comments