-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient-node-protocol.mjs
65 lines (56 loc) · 1.58 KB
/
client-node-protocol.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import {sack} from "sack.vfs";
import {Events} from "../events/events.mjs"
const JSOX = sack.JSOX;
export class Protocol extends Events {
static debug = true;
ws = null;
protocol = null;
constructor( address, protocol ){
super();
this.address = address;
this.protocol = protocol;
if( protocol )
this.connect(protocol, this);
}
set debug(val) { Protocol.debug = val; }
get debug() { return Protocol.debug; }
connect(protocol, this_) {
if( this.ws ) this.ws.close( 1006, "close duplicate socket" );
this.ws = new sack.WebSocket.Client( this.address, protocol );
this.ws.onmessage = (msg)=>this.onmessage(msg) ;
this.ws.onclose = (code,reason)=>this.onclose(code,reason) ;
this.ws.onopen = (msg)=>this.onopen.call( evt) ;
this.ws.onerror = (msg)=>this.onerror.call( evt) ;
return this.ws;
}
onopen( evt ) {
this.on( "open", true );
}
onerror( evt ) {
this.on( "error", evt );
}
onclose( evt ){
Protocol.debug && console.log( "close?", this, evt );
this.on( "close", [evt.code, evt.reason] );
this.ws = null;
if( evt.code === 1000 ) this.connect();
else setTimeout( this.connect, 5000 );
}
onmessage( evt ) {
Protocol.debug && console.log( "got:", this, evt );
const msg = JSOX.parse( evt.data );
if( !this.on( msg.op, msg ) ){
console.log( "Unhandled message:", msg );
}
}
send( msg ) {
if( Protocol.ws.readyState === 1 ) {
if( "object" === typeof msg )
this.ws.send( JSOX.stringify(msg) );
else
this.ws.send( msg );
} else {
console.log( "Protocol socket is not in open readystate", this.ws.readyState );
}
}
}