-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.js
86 lines (74 loc) · 2.05 KB
/
websocket.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
86
import { handleResponse } from "./guiapi.js"
class Stream {
constructor(url) {
this.url = url
this.socket = null
this.open = false
this.closed = false
this.current = null
this.tries = 0
}
subscribe = (data) => {
console.log("Stream.subscribe()", data)
this.tries = 0
if (this.open) {
this.current = data
this.socket.send(JSON.stringify(data))
return
}
this.current = data
if (!this.socket) {
this.connect()
}
}
connect = () => {
console.log("websocket connecting:", this.url, "try:", this.tries)
this.tries++
const socket = new WebSocket(this.url, "guiapi")
socket.>
socket.>
socket.>
socket.>
this.socket = socket
}
=> {
console.log("websocket opened:", event);
this.tries = 0
this.open = true
this.socket.send(JSON.stringify(this.current))
}
=> {
const res = JSON.parse(event.data)
console.log("stream message:", res)
handleResponse(res, (err) => {
if (err) {
console.error("websocket handleResponse error:", err)
}
})
}
=> {
this.open = false
this.socket = null
console.log("websocket closed:", event);
if (this.closed) {
return
}
if (this.tries < 3) {
this.connect()
} else {
console.log("stopped reconnecting after 3 tries")
}
}
=> {
// this.open = false ???
console.log("websocket error:", event);
}
}
const streamHandler = new Stream("ws://localhost:8000/guiapi/ws");
export function handleStream(stream) {
console.log("guiapi handleStream:", stream)
streamHandler.subscribe(stream)
}
export default {
handleStream
}
You can’t perform that action at this time.