-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.ts
More file actions
37 lines (27 loc) · 965 Bytes
/
Copy pathwebsocket.ts
File metadata and controls
37 lines (27 loc) · 965 Bytes
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
import * as io from "socket.io-client"
let socket: io.Socket
export function sendClient(url: string, action: string, data: any = {}) {
if (!socket || socket.disconnected) connect(url)
socket.emit("data", JSON.stringify({ action, ...data }))
}
function connect(url: string) {
socket = io.connect(url, { reconnection: true, transports: ["websocket"] })
console.log(`Searching for WebSocket server at ${url}...`)
addListeners()
}
export function closeClient() {
if (!socket) return
socket.close()
console.log("Connection closed!")
}
function addListeners() {
socket.on("connect", () => {
console.log("Connected to FreeShow!")
})
socket.on("disconnect", () => console.log("Lost connection."))
socket.on("error", (err: any) => console.log(`Error message from server: ${err}`))
socket.on("data", (data: any) => {
console.log("Data received:", data)
// data = JSON.parse(data)
})
}