-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient-protocol.js
86 lines (74 loc) · 2.45 KB
/
client-protocol.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import {Events} from "../events/events.mjs"
import {JSOX} from "/node_modules/jsox/lib/jsox.mjs"
export class Protocol extends Events {
static debug = false;
protocol = null;
server = new URL(import.meta.url).origin.replace("http","ws") || location.origin.replace("http","ws");
#Protocol = Protocol; // this is the proper class container of the implemented protocol
get debug() {
return Protocol.debug;
}
set debug(val) {
Protocol.debug = val;
}
constructor( protocol, server ){
super();
if( server ) this.server = server.replace("http","ws");
this.#Protocol = Object.getPrototypeOf( this ).constructor;
this.#Protocol.ws = null; // allocate static ws member.
this.protocol = protocol;
if( protocol )
Protocol.connect(protocol, this);
}
static connect(protocol, this_) {
const ThisProtocol = this_.#Protocol;//Object.getPrototypeOf( this ).constructor;
const source = new URL( import.meta.url ).origin
ThisProtocol.ws = new WebSocket( this_.server, protocol );
ThisProtocol.ws.onmessage = (evt)=>Protocol.onmessage.call( this_, evt) ;
ThisProtocol.ws.onclose = (evt)=>Protocol.onclose.call( this_, evt) ;
ThisProtocol.ws.onopen = (evt)=>Protocol.onopen.call( this_, evt) ;
return ThisProtocol.ws;
}
get ready() {
if( this.#Protocol.ws )
if( this.#Protocol.ws.readyState == 1 ) return true;
return false;
}
connect() {
return Protocol.connect( this.protocol, this );
}
static onopen( evt ) {
const ThisProtocol = Object.getPrototypeOf( this ).constructor;
ThisProtocol.on( "open", true );
this.on( "open", true );
}
static onclose( evt ){
const Protocol = Object.getPrototypeOf( this ).constructor;
Protocol.debug && console.log( "close?", this, evt );
const event = this.on( "close", [evt.code, evt.reason] );
Protocol.ws = null;
if( evt.code === 1000 ) this.connect();
else setTimeout( this.connect.bind(this), 5000 );
}
static onmessage( evt ) {
Protocol.debug && console.log( "got:", this, evt );
const msg = JSOX.parse( evt.data );
if( !this.on( msg.op, msg ) ){
Protocol.debug && console.log( "Unhandled message:", msg );
}
}
send( msg ) {
const ws = this.#Protocol.ws;
if( ws && ws.readyState === 1 ) {
if( "object" === typeof msg ) {
ws.send( JSOX.stringify(msg) );
} else
ws.send( msg );
} else {
Protocol.debug && console.log( "Protocol socket is not in open readystate", ws.readyState );
}
}
close( code, reason ) {
return this.ws.close( code, reason );
}
}