multiple-websocketsFOSSA Statusinstall size

a React Component or Hook which allow multiple websocket connections.

  • Always keep one communication when repeatly open the same websocket url
  • Allow multiple communication when open the different urls
  • Supports multiple pages/components processing the communication with the same url

Install

1
2
3
$ npm i multiple-websockets --save
or
$ yarn add multiple-websockets

Example

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
import { Component,useEffect } from "react";
import { WebSocket as ws, useWebsocket } from "multiple-websockets";

const wsUrl = "ws://localhost:8001";
class Com1 extends Component {
//open callback
openCB = (e) => {};
//message callback
messageCB = (e) => {};
//close callback
closeCB = (e) => {};
//error callback
errorCB = (e) => {};

open = () => {
ws.open(wsUrl, 5, this.openCB, this.messageCB, this.closeCB, this.errorCB);
};
send = () => {
ws.sendMessage(wsUrl, "test123");
};
close = () => {
ws.close(wsUrl);
};

render() {
return (
<>
<button onClick={this.open}>open</button>
<button onClick={this.send}>send</button>
<button onClick={this.close}>close</button>
</>
);
}
}

function Com2() {
const [message, open, send, close] = useWebsocket(wsUrl, 5);
useEffect(() => {
// message
}, [message]);
return (
<>
<button onClick={open}>open</button>
<button onClick={send}>send</button>
<button onClick={close}>close</button>
</>
);
}

function App() {
return (
<>
<h1>class</h1>
<Com1 />
<h1>hook</h1>
<Com2 />
</>
);
}

Lisctens

FOSSA Status