-
Notifications
You must be signed in to change notification settings - Fork 22
/
useClient.ts
38 lines (35 loc) · 1.05 KB
/
useClient.ts
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
import { useEffect, useState } from "react";
import { Platform } from "react-native";
const ANDROID_WS_HOST = "10.0.2.2";
const IOS_WS_HOST = "localhost";
const HOST = Platform.OS === "android" ? ANDROID_WS_HOST : IOS_WS_HOST;
const PORT = 4242;
type UseClient = [client: WebSocket | null, hostname: string];
export const useClient = (): UseClient => {
const [client, setClient] = useState<WebSocket | null>(null);
const [retry, setRetry] = useState<number>(0);
useEffect(() => {
const url = `ws://${HOST}:${PORT}`;
let it: ReturnType<typeof setTimeout>;
const ws = new WebSocket(url);
ws.onopen = () => {
setClient(ws);
ws.send(JSON.stringify({ OS: Platform.OS, arch: "paper" }));
};
ws.onclose = () => {
setClient(null);
};
ws.onerror = () => {
it = setTimeout(() => {
ws.close();
// incrementing retry to rerun the effect
setRetry((r) => r + 1);
}, 500);
};
return () => {
ws.close();
clearTimeout(it);
};
}, [retry]);
return [client, HOST];
};