Nginx Proxy ManagerÓëWebSocketµÄ¸ßЧͨѶʵÏÖ
Nginx Proxy Manager£¨ÒÔϼò³ÆNPM£©ÊÇÒ»¸ö»ùÓÚNginxµÄÊðÀíÖÎÀí¹¤¾ß£¬ËüÌṩÁËÒ»ÖÖ¼òÆÓ¶øÇ¿Ê¢µÄ·½·¨À´ÖÎÀí¶à¸ö·´ÏòÊðÀíЧÀÍÆ÷¡£×î½ü£¬ÎÒÔÚʹÓÃNPMʱÓöµ½ÁËÒ»¸öÎÊÌ⣺ÔõÑùʵÏÖNPMÓëWebSocketµÄ¸ßЧͨѶ¡£ÔÚ±¾ÎÄÖУ¬ÎÒ½«·ÖÏíÎÒÔÚʵÏÖÕâһĿµÄʱËù»ñµÃµÄÂÄÀúºÍ½Ìѵ£¬²¢ÌṩÏêϸµÄ´úÂëʾÀý¡£
ÔÚ×îÏÈ֮ǰ£¬ÈÃÎÒÃǼòÒªÏàʶһÏÂWebSocket¡£WebSocketÊÇÒ»ÖÖÔÚµ¥¸öTCPÅþÁ¬ÉϾÙÐÐÈ«Ë«¹¤Í¨Ñ¶µÄÐÒé¡£ÓëHTTP²î±ð£¬WebSocketÔÊÐíЧÀÍÆ÷×Ô¶¯Ïò¿Í»§¶Ë·¢ËÍÊý¾Ý£¬¶ø²»ÐèÒª¿Í»§¶Ë·¢³öÇëÇó¡£ÓÉÓÚÆäµÍÑӳٺ͸ßЧÐÔ£¬WebSocketÔÚʵʱӦÓóÌÐòÖкÜÊÇÊܽӴý£¬ºÃ±È̸ÌìÓ¦Óá¢ÊµÊ±Êý¾Ý´«ÊäµÈ¡£
NPMʹÓÃNginxÀ´´¦Öóͷ£HTTPºÍHTTPSÇëÇ󣬲¢Ìṩ·´ÏòÊðÀí¹¦Ð§¡£ÎªÁËʵÏÖÓëWebSocketµÄ¸ßЧͨѶ£¬ÎÒÃÇÐèÒª½«NPMÉèÖÃΪ¿ÉÒÔת·¢WebSocketÇëÇó²¢×¼È·´¦Öóͷ£Ïà¹ØÍ·²¿ÐÅÏ¢¡£ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄNginxÉèÖÃʾÀý£º
server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location /ws/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location /api/ { ... } location /admin/ { ... } ... upstream backend { server backend.example.com; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÉèÖÃÖУ¬ÎÒÃÇʹÓÃÁËÁ½¸ölocation¿éÀ´´¦Öóͷ£WebSocketÇëÇó¡£µÚÒ»¸ölocation¿éÓÃÓÚ´¦Öóͷ£¸ù·¾¶ÏµÄWebSocketÇëÇ󣬶øµÚ¶þ¸ölocation¿éÓÃÓÚ´¦Öóͷ£ÒÔ/ws/¿ªÍ·µÄWebSocketÇëÇó¡£ÔÚÕâÁ½¸ölocation¿éÖУ¬ÎÒÃÇʹÓÃÁËproxy_passÖ¸ÁÇëÇóת·¢¸øºó¶ËЧÀÍÆ÷£¬²¢ÉèÖÃÁËÏà¹ØHTTPÍ·²¿ÐÅÏ¢£¬ÒÔÈ·±£WebSocketÇëÇóÄܹ»×¼È·µØת´ïµ½ºó¶ËЧÀÍÆ÷¡£
³ýÁËÉèÖÃNginx£¬ÎÒÃÇ»¹ÐèÒªÔÚºó¶ËЧÀÍÆ÷ÉÏʵÏÖWebSocketµÄÏà¹ØÂß¼¡£ÏÂÃæÊÇÒ»¸öʹÓÃNode.jsºÍWebSocket¿âʵÏֵļòÆÓʾÀý£º
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (message) => { console.log(`Received: ${message}`); }); ws.send('Hello, client!'); });
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃǽ¨ÉèÁËÒ»¸öWebSocketЧÀÍÆ÷£¬²¢ÔÚconnectionÊÂÎñÖд¦Öóͷ£ÐµÄÅþÁ¬¡£ÔÚconnectionÊÂÎñ´¦Öóͷ£³ÌÐòÖУ¬ÎÒÃÇ¿ÉÒÔ´¦Öóͷ£À´×Ô¿Í»§¶ËµÄÐÂÎÅ£¬²¢·¢ËÍÏìÓ¦¡£
ʹÓÃÉÏÊöNginxÉèÖúÍWebSocketЧÀÍÆ÷´úÂ룬ÎÒÃÇ¿ÉÒÔʵÏÖNPMÓëWebSocketµÄ¸ßЧͨѶ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃNPMÀ´´¦Öóͷ£HTTPÇëÇ󣬲¢½«Ìض¨URLÉϵÄWebSocketÇëÇóת·¢µ½ºó¶ËWebSocketЧÀÍÆ÷¡£ÕâÑù£¬ÎÒÃǾͿÉÒÔÔÚͳһ¸öÓòÃûÏÂͬʱʹÓÃHTTPºÍWebSocket£¬²¢ÇÒWebSocketÇëÇó¿ÉÒÔÓëÆäËûHTTPÇëÇóÒ»Ñù±»NPMÖÎÀí¡£
×ÛÉÏËùÊö£¬Í¨¹ýÊʵ±ÉèÖÃNPMºÍʵÏÖºó¶ËWebSocketЧÀÍÆ÷µÄ´úÂ룬ÎÒÃÇ¿ÉÒÔʵÏÖNPMÓëWebSocketµÄ¸ßЧͨѶ¡£ÕâʹµÃÎÒÃÇÄܹ»ÔÚʹÓÃNPMµÄͬʱ£¬ÇáËÉ´¦Öóͷ£WebSocketÇëÇ󣬲¢ÊµÏÖʵʱӦÓóÌÐòËùÐèµÄʵʱͨѶ¹¦Ð§¡£Ï£Íû±¾ÎĵĴúÂëʾÀýÏ¢ÕùÊͶÔÄúÓÐËù×ÊÖú£¡
ÒÔÉϾÍÊÇNginx Proxy ManagerÓëWebSocketµÄ¸ßЧͨѶʵÏÖµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡