Skip to content

Commit 7736381

Browse files
committed
Add Async Client Websocket files
1 parent 4cc1420 commit 7736381

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/AsyncClientWebSocket.js

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*!
2+
* Async Client Websocket v1.0.3
3+
* by Jean Kássio
4+
*
5+
* More info:
6+
* https://jeankassio.dev
7+
*
8+
* Copyright Jean Kássio
9+
* Released under the MIT license
10+
* https://github.com/jeankassio/Async-Client-Websocket/blob/main/LICENSE
11+
*
12+
* @preserve
13+
*/
14+
15+
class WebSocketClient {
16+
constructor(url) {
17+
this.url = url;
18+
this.socket = null;
19+
this.onOpen = null;
20+
this.onClose = null;
21+
this.onMessage = null;
22+
this.onError = null;
23+
}
24+
25+
connect() {
26+
return new Promise((resolve, reject) => {
27+
this.socket = new WebSocket(this.url);
28+
29+
this.socket.onopen = (event) => {
30+
if (this.onOpen) {
31+
this.onOpen(event);
32+
}
33+
resolve();
34+
};
35+
36+
this.socket.onmessage = (event) => {
37+
const message = event.data;
38+
if (this.onMessage) {
39+
this.onMessage(message);
40+
}
41+
};
42+
43+
this.socket.onerror = (error) => {
44+
if (this.onError) {
45+
this.onError(error);
46+
}
47+
};
48+
49+
this.socket.onclose = (event) => {
50+
if (this.onClose) {
51+
this.onClose(event);
52+
}
53+
};
54+
});
55+
}
56+
57+
send(message) {
58+
if(this.socket && this.socket.readyState === WebSocket.OPEN) {
59+
this.socket.send(message);
60+
}
61+
}
62+
63+
disconnect() {
64+
if (this.socket) {
65+
this.socket.close();
66+
}
67+
}
68+
}

src/AsyncClientWebSocket.min.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/*!
2+
* Async Client Websocket v1.0.3
3+
* by Jean Kássio
4+
*
5+
* More info:
6+
* https://jeankassio.dev
7+
*
8+
* Copyright Jean Kássio
9+
* Released under the MIT license
10+
* https://github.com/jeankassio/Async-Client-Websocket/blob/main/LICENSE
11+
*
12+
* @preserve
13+
*/ class WebSocketClient{constructor(s){this.url=s,this.socket=null,this.onOpen=null,this.onClose=null,this.onMessage=null,this.onError=null}connect(){return new Promise((s,t)=>{this.socket=new WebSocket(this.url),this.socket.onopen=t=>{this.onOpen&&this.onOpen(t),s()},this.socket.onmessage=s=>{let t=s.data;this.onMessage&&this.onMessage(t)},this.socket.onerror=s=>{this.onError&&this.onError(s)},this.socket.onclose=s=>{this.onClose&&this.onClose(s)}})}send(s){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send(s)}disconnect(){this.socket&&this.socket.close()}}

0 commit comments

Comments
 (0)