websocket.js is a WebSocket tool class on the WEB side
1. Function introduction
1.1 Disconnection and reconnection
- When hanging up normally, the disconnection will automatically reconnect
- When sending a message, the disconnection will automatically reconnect, and the previous message will be sent after the connection is successful
1.2 Built-in heartbeat
- Automatically send heartbeat messages
- When using onmessage to receive messages, heartbeat messages will be automatically filtered out, that is, heartbeat messages on the server side will not enter the rewritten onmessage method
2. Code usage
2.1 Import js
<script src="https://gitee.com/mail_osc/websocket.js/raw/master/websocket.js"></script>
2.2 Code
websocket.connect({ url:'wss://api.kefu.leimingyun.com/websocket', //服务端的WebSocket地址 onopen:function(){ //如果不需要,此不传即可。 websocket.send({"type":"CONNECT","token":"123456"}); //当WebSocket通道连接成功后,自动给服务器发送一条json格式的消息 }, onmessage:function(message){ //如果不需要,此不传即可 console.log(message); //服务端发送来的消息会在这里接收到 } });
3. Process diagram
4. Interface description
4.1 websocket.send(…) Send a message to the server
The parameters can be in string format or json format, which are automatically recognized.Recommended json format
4.2 websocket.heartBeat.text heartbeat message content
You can customize the content of the heartbeat message sent to the server. The default value is: {"type":"HEARTBEAT","text":"AreYouThere"}
The setting method is as follows:
websocket.heartBeat.text = '{"type":"HEARTBEAT","text":"AreYouThere"}';
4.3 websocket.heartBeat.time heartbeat message interval time
You can customize the interval for sending heartbeat messages to the server, in seconds, and automatically send a heartbeat message to the server every second. The default value is 40, which is 40 seconds.
The setting method is as follows:
websocket.heartBeat.time = 40;
4.4 websocket.ws WebSocket object of JS itself
You can directly use websocket.ws to get the WebSocket object of its JS itself for more use
5. About us
Author: Guan Leiming
#Leiming #websocketjs #Homepage #Documentation #Download #WebSocket #Tools #News Fast Delivery