File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ import * as WebSocket from "ws" ;
2+
3+ export default class Loadbalancer {
4+ public host : string ;
5+ public accessToken : string ;
6+ public interval ?: number ;
7+ public gateway ?: WebSocket ;
8+ public _interval ?: NodeJS . Timer ;
9+ public static OpcodeHello : number = 10 ;
10+
11+ constructor ( accessToken : string , host : string ) {
12+ this . host = host ;
13+ this . accessToken = accessToken ;
14+ }
15+
16+ emitStats ( ) : void {
17+ if ( ! this . gateway || this . gateway . readyState !== WebSocket . OPEN )
18+ throw new Error ( "Gateway connection not open" ) ;
19+ this . gateway . send ( JSON . stringify ( {
20+ t : "stats" ,
21+ d : JSON . stringify ( {
22+ accessToken : this . accessToken ,
23+ // todo...
24+ mem : 0 ,
25+ cpu : 0
26+ } )
27+ } ) ) ;
28+ }
29+
30+ connect ( customHost ?: string ) : WebSocket {
31+ this . gateway = new WebSocket ( customHost || this . host ) ;
32+
33+ this . gateway . on ( "message" , data => {
34+ const parsed : any = JSON . parse ( data . toString ( ) ) ;
35+ if ( parsed . op === Loadbalancer . OpcodeHello ) {
36+ this . interval = parseInt ( parsed . d ) ;
37+ this . _interval = setInterval ( ( ) => this . emitStats ( ) , this . interval ) ;
38+ }
39+ } ) ;
40+
41+ this . gateway . on ( "close" , ( ) => {
42+ clearInterval ( this . _interval ) ;
43+ } ) ;
44+
45+ return this . gateway ;
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments