Websocket features:
1. Ws (non-encryption) and WSS (encryption); Ws establishes a handshake based on HTTP requests, WSS establishes a handshake based on HTTPS requests. 2. The HANDSHAKE of THE WS is based on the HTTP GET mode, and the protocol must be no less than 1.1. 3. Ws and WSS request headers have many more special headers than pure HTTP request headers. 4. Ws request After the connection is established, both communication parties can send data to the other party at any time. (HTTP can only send requests to the server client) the basic usage of websocket is not introduced here, there are many related articles on the Internet, in this post a good link address. The w3c introduction to websocket: www.runoob.com/html/html5-…
Project Configuration:
// Modify the vue.config.js file
devServer: {
open: true.// Open it in the browser after startup
proxy: {
'/api': { // Set a normal HTTP proxy
target: 'http://x.x.x.x:8080'.changeOrigin: true.pathRewrite: {
'^/api': ' '}},'/socket': { // Set the WebSocket proxy
target: 'http://x.x.x.x:8080'.ws: true.// Enable the webSocket proxy
changeOrigin: true.pathRewrite: {
'^/socket': ' '}}}}Copy the code
Vue single-page
export default {
data () {
return {
socket: null.connectCount: 0.// Number of connections
heartInterval: null
}
},
created () {
this.initSocket()
},
methods: {
/** * The connection is HTTP ** the message push is TCP connection, there is no origin limit ** server try catch message push failed, then close the connection */
initSocket () {
const { protocol, host } = location
const url = `${protocol === 'https' ? 'wss' : 'ws'}: / /${host}/socket/websocket/mineStatus/The ${this.$store.getters.userId}`
// Check whether the current browser supports WebSocket
if (typeof WebSocket === 'undefined') {
this.$notification.warning({
message: 'System info'.description: 'Your browser does not support sockets'.duration: 4
})
return
}
this.socket = new WebSocket(url)
this.socket.onmessage = (evt) = > {
if (evt.data === 'Connection successful' || evt.data.includes('refresh')) {
this.heartCheck() // Reset heartbeat detection
// this.onrefresh () receives a push message to refresh the list}}// Listen for window events and disconnect webSocket when the window is closed
window.onbeforeunload = () = > {
this.closeSocket()
}
},
/** * Send heartbeat packets at regular intervals * 59s send a heartbeat, a little shorter than the maximum connection time set by nginx, to reset the connection time at critical points */
heartCheck () {
const _this = this
this.heartInterval && clearTimeout(this.heartInterval)
this.heartInterval = setInterval(() = > {
if (this.socket.readyState === 1) { // Connection status
this.socket.send('ping')}else {
_this.connectCount += 1
if (_this.connectCount <= 5) {
this.initSocket() // Break point reconnection 5 times}}},59 * 1000)},/** Disconnect the websocket */
closeSocket() {
this.socket.close()
this.heartInterval && clearTimeout(this.heartInterval)
}
},
destroyed() {
this.closeSocket()
}
}
Copy the code
Ps: When the client network is not good or disconnected, the server will still push messages to the client without knowing about it, resulting in a waste of resources. Therefore, the back-end server has to do exception handling, and when the message push fails, it actively closes the Websocket connection.
Nginx configuration
http {
map $http_upgrade $connection_upgrade {
default upgrade;
' ' close;
}
server {
listen 8084;
server_name _;
root /usr/share/nginx/html/pcNet;
include /etc/nginx/default.d/*.conf; location ^~/socket/ { proxy_pass http://x.x.x.x:8080/; Proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade websocket; proxy_set_header Connection Upgrade; } location ^~/api/ { proxy_pass http://x.x.x.x:8080/; }... }}Copy the code
Parameters: proxy_pass: indicates the URL to be proxyed. roxy_http_version: indicates the HTTP version to be used for proxyed. proxy_set_header Host: Proxy_set_header x-Forwarded-for: $remote_addr proxy_set_header x-Forwarded-for: $remote_addr Proxy_set_header x-Forwarded-For: Reverse proxy after forwarding the previous IP address proxy_set_header Upgrade: Set the Upgrade of the HTTP request header to the original HTTP request header, and the WSS request header is websocket proxy_set_header Connection: Because of the proxy’s WSS protocol, the Connection of the HTTP request header is set to Upgrade. HTTPS is encrypted request, need SSL encryption, so nginx support HTTPS, need to configure the SSL links in this post out solutions www.cnblogs.com/zhoudawei/p…