Nginx reverse proxy WebSocket configuration to achieve real-time communication
WebSocket is a network protocol that supports full-duplex communication. It can establish a persistent connection between the client and the server to achieve real-time communication. Nginx is a high-performance web server and reverse proxy server. Through the reverse proxy configuration of Nginx, you can proxy WebSocket requests to the back-end server, thereby realizing the real-time communication function of WebSocket.
Here is an example on how to configure Nginx reverse proxy WebSocket:
server { listen 80; server_name your_server_domain; location / { proxy_pass http://your_backend_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
Among them, your_server_domain is the domain name or IP address of the server, and your_backend_server is the address and port of the backend server.
sudo service nginx restart
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { console.log('New client connected'); ws.on('message', message => { console.log(`Received message: ${message}`); }); ws.on('close', () => { console.log('Client disconnected'); }); });
The above code creates a WebSocket server, prints a log when each new client connects, and receives and print relevant information respectively when closing the connection.
Through the above steps, we successfully configured the reverse proxy of Nginx and implemented the real-time communication function of WebSocket.
Summary: Nginx reverse proxy WebSocket configuration can proxy WebSocket requests to the back-end server, making real-time communication possible. Through the above steps, we can easily configure Nginx to support WebSocket and write code on the backend server to handle WebSocket requests. In this way, we can use the high performance and stability of Nginx to achieve real-time communication functions.
The above is the detailed content of Nginx reverse proxy WebSocket configuration to achieve real-time communication. For more information, please follow other related articles on the PHP Chinese website!