1 | const createSocket = function({ key, host, onmessage }) {
|
2 | const ReconnectingWebSocket = require("reconnecting-websocket");
|
3 | try {
|
4 | const path = host.replace("http:", "");
|
5 | const webSocketPath = "ws:" + path + "websocket";
|
6 | let webSocket = new ReconnectingWebSocket(webSocketPath);
|
7 | webSocket.debug = true;
|
8 | webSocket.timeoutInterval = 5400;
|
9 | window.onbeforeunload = function() {
|
10 | webSocket.close();
|
11 | };
|
12 | webSocket.onopen = function() {
|
13 | webSocket.send(key);
|
14 | };
|
15 | webSocket.onmessage = event => {
|
16 | const push = JSON.parse(event.data);
|
17 | if (process.env.NODE_ENV !== "production") {
|
18 | console.log("push >>", push);
|
19 | }
|
20 | onmessage(push);
|
21 | };
|
22 | } catch (e) {
|
23 | console.log("Your Browser Not Support WebSocket");
|
24 | }
|
25 | };
|
26 |
|
27 | export default createSocket;
|