Precautions for the use of WebSocket
1. Domain name configuration
Hard requirements for WeChat Mini Program
2.Https certificate
Hard requirements for WeChat Mini Program
3.Nginx configuration
Nginx configuration is different from ordinary interfaces. WebSocket requires some special configuration.
If yes 集群
, remember to configure 会话保持
orhaspip
4. Backend
I use Netty-Socket-IO
framework coordination for the back end SpringBoot
.
The back-end code can see this article of mine
5. Mini terminal
Test code
wx.connectSocket({
// 小程序端,必须使用wss协议,也就是说服务器必须要配置https证书。
url: 'wss://*****/socket.io/?userId=123&EIO=3&transport=websocket',
success: function (res) {
console.log('Socket连接成功:', res);
},
fail: function (res) {
console.error('连接失败:', res);
},
})
wx.onSocketOpen(() => {
console.log('监听到 WebSocket 连接已打开!');
wx.sendSocketMessage({
data: "2probe"
});
})
wx.onSocketError(data => {
console.log(data);
})
wx.onSocketMessage(data => {
let code = data.data.substr(0, 1);
console.log(code)
if (code === "0") {
let d1 = {
"sid": JSON.parse(data.data.substr(1, data.data.length)).sid
};
wx.sendSocketMessage({
data: d1})
}else if (code === "3"){
setTimeout((function callback() {
wx.sendSocketMessage({
data: "2"
});
}).bind(this), 5000)
}else if (code === "2") {
wx.sendSocketMessage({
data: "3"
});
}
console.log(data)
})
7. H5 client
Test code
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('https://*********.cn/socket.io?userId=1', {
'reconnection delay' : 2000,
'force new connection' : true
});
socket.on('message', function(data) {
// here is your handler on messages from server
console.log(data)
});
socket.on('chatevent', function(data) {
// here is your handler on chatevent from server
console.log(data)
});
socket.on('connect', function() {
// connection established, now we can send an objects
// send json-object to server
// '@class' property should be defined and should
// equals to full class name.
// var obj = {
'@class' : 'com.sample.SomeClass'
// }
// socket.json.send(obj);
// send event-object to server
// '@class' property is NOT necessary in this case
var event = {
}
// socket.emit('someevent', event);
});
</script>
socket.io.js
, Automatically keep replying.
6. Matters needing attention
The WebSocket of the applet needs to maintain the link by itself.
If the applet terminal wants to maintain the reply by itself, it needs to develop itself according to the agreement.
Socket协议
0:open
1:close
2:ping
3:pong
4:message
5:upgrade
6:noop
As can be seen from the above figure, 2、3
the protocol reply encapsulated by js on the H5 side .