Nginx·´ÏòÊðÀíWebSocketÉèÖã¬ÊµÏÖʵʱͨѶ
nginx·´ÏòÊðÀíwebsocketÉèÖã¬ÊµÏÖʵʱͨѶ
WebSocketÊÇÒ»ÖÖÖ§³ÖÈ«Ë«¹¤Í¨Ñ¶µÄÍøÂçÐÒ飬ËüÄÜÔÚ¿Í»§¶ËºÍЧÀÍÆ÷Ö®¼ä½¨É賤ÆÚÅþÁ¬£¬ÊµÏÖʵʱͨѶ¡£NginxÊÇÒ»¿î¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬Í¨¹ýNginxµÄ·´ÏòÊðÀíÉèÖ㬿ÉÒÔʵÏÖ½«WebSocketÇëÇóÊðÀíµ½ºó¶ËЧÀÍÆ÷ÉÏ£¬´Ó¶øʵÏÖWebSocketµÄʵʱͨѶ¹¦Ð§¡£
ÏÂÃæÊÇÒ»¸ö¹ØÓÚÔõÑùÉèÖÃNginx·´ÏòÊðÀíWebSocketµÄʾÀý£º
×°ÖÃNginx
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚЧÀÍÆ÷ÉÏ×°ÖÃNginx¡£¿ÉÒÔʹÓðü¹ÜÀí¹¤¾ß£¨Èçapt¡¢yumµÈ£©¾ÙÐÐ×°Öá£×°ÖÃÍê³Éºó£¬¿ÉÒÔͨ¹ýÔËÐС°nginx -v¡±ÏÂÁîÀ´¼ì²éNginxµÄ×°Öð汾¡£
ÉèÖÃNginx
ÉèÖÃNginxµÄ·´ÏòÊðÀí£¬Ê¹ÆäÄܹ»½«WebSocketÇëÇóת·¢µ½ºó¶ËЧÀÍÆ÷¡£·¿ªNginxµÄÉèÖÃÎļþ£¬Ò»Ñùƽ³£Î»ÓÚ¡°/etc/nginx/nginx.conf¡±»ò¡°/etc/nginx/conf.d/default.conf¡±Â·¾¶Ï£¬Ìí¼ÓÒÔÏÂÉèÖãº
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"; } }
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬your_server_domainÊÇЧÀÍÆ÷µÄÓòÃû»òIPµØµã£¬your_backend_serverÊǺó¶ËЧÀÍÆ÷µÄµØµãºÍ¶Ë¿Ú¡£
ÖØÆôNginx
Íê³ÉÉèÖúó£¬ÐèÒªÖØÆôNginxЧÀÍÆ÷£¬Ê¹ÉèÖÃÉúЧ¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´ÖØÆôNginx£º
sudo service nginx restart
µÇ¼ºó¸´ÖÆ
ºó¶ËЧÀÍÆ÷
ÔÚºó¶ËЧÀÍÆ÷ÉÏ£¬ÐèÒª±àдÄܹ»´¦ÀíWebSocketÇëÇóµÄ´úÂë¡£ÕâÀïÒÔNode.jsΪÀý£¬½¨ÉèÒ»¸ö¼òÆÓµÄWebSocketЧÀÍÆ÷£º
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'); }); });
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂ뽨ÉèÁËÒ»¸öWebSocketЧÀÍÆ÷£¬ÔÚÿ¸öеĿͻ§¶ËÅþÁ¬Ê±´òÓ¡Ò»ÌõÈÕÖ¾£¬²¢ÔÚÊÕµ½ºÍ¹Ø±ÕÅþÁ¬Ê±»®·Ö´òÓ¡Ïà¹ØÐÅÏ¢¡£
²âÊÔ
ÏÖÔÚ£¬ÎÒÃÇ¿ÉÒÔʹÓÃWebSocket¿Í»§¶Ë¹¤¾ß£¨Èçä¯ÀÀÆ÷µÄ¿ª·¢Õß¹¤¾ß¡¢PostmanµÈ£©À´²âÊÔWebSocketµÄʵʱͨѶ¹¦Ð§¡£Í¨¹ýÏòNginxЧÀÍÆ÷·¢ËÍWebSocketÇëÇó£¬Nginx½«ÇëÇóת·¢µ½ºó¶ËЧÀÍÆ÷¾ÙÐд¦Àí¡£
ͨ¹ýÒÔÉÏ°ì·¨£¬ÎÒÃÇÀֳɵØÉèÖÃÁËNginxµÄ·´ÏòÊðÀí£¬ÊµÏÖÁËWebSocketµÄʵʱͨѶ¹¦Ð§¡£
×ܽ᣺Nginx·´ÏòÊðÀíWebSocketÉèÖÃÄܹ»ÊµÏÖ½«WebSocketÇëÇóÊðÀíµ½ºó¶ËЧÀÍÆ÷ÉÏ£¬Ê¹µÃʵʱͨѶ³ÉΪ¿ÉÄÜ¡£Í¨¹ýÒÔÉÏ°ì·¨£¬ÎÒÃÇÄܹ»ÇáËɵØÉèÖÃNginxÀ´Ö§³ÖWebSocket£¬²¢ÔÚºó¶ËЧÀÍÆ÷Éϱàд´¦ÀíWebSocketÇëÇóµÄ´úÂë¡£ÕâÑù£¬ÎÒÃǾͿÉÒÔ½èÖúNginxµÄ¸ßÐÔÄܺÍÎȹÌÐÔ£¬ÊµÏÖʵʱͨѶµÄ¹¦Ð§¡£
ÒÔÉϾÍÊÇNginx·´ÏòÊðÀíWebSocketÉèÖã¬ÊµÏÖʵʱͨѶµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡