-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket-ports.js
44 lines (33 loc) · 1.09 KB
/
websocket-ports.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
// LOWLEVEL websocket stuff in javascript
function websocketBindPorts(ports) {
// PORTS
ports.webSocketOpen.subscribe(open); // String -> Cmd msg
ports.webSocketSend.subscribe(send); // (Value, Value) -> Cmd msg
ports.webSocketClose.subscribe(close); // (Value, Int, String) -> Cmd msg
//COMMANDS
function open(url) {
const ws = new WebSocket(url);
ws.onclose = sendToElm('webSocketOnClose');
ws.onerror = sendToElm('webSocketOnError');
ws.onmessage = sendToElm('webSocketOnMessage');
ws.onopen = sendToElm('webSocketOnOpen');
function sendToElm(port) {
return function (event) {
if (ports[port] && ports[port].send) {
ports[port].send(event)
}
}
}
}
function send(param) {
const ws = param[0];
const data = param[1];
ws.send(JSON.stringify(data));
}
function close(param) {
const ws = param[0];
const code = param[1];
const reason = param[2];
ws.close(ws, code, reason);
}
}