NginxÔõÑùʵÏÖWebSocketÉèÖÃ
Nginx×÷Ϊһ¿î¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬ÔÚ´¦ÀíWebSocketÇëÇó·½ÃæÒ²ÓÐÆäÆæÒìµÄÉèÖ÷½·¨¡£WebSocket£¬ÊÇÒ»ÖÖ»ùÓÚTCPµÄÐÒ飬WebSocketÅþÁ¬µÄ½¨ÉèÐèÒª¾ÓÉÈý´ÎÎÕÊÖ£¬ÎÕÊÖÍê³Éºó£¬¿Í»§¶ËºÍЧÀÍÆ÷Ö®¼ä¿ÉÒÔ¾ÙÐÐË«ÏòͨѶ¡£ÏÂÃ棬½«ÏÈÈÝÔõÑùÔÚNginxÖÐʵÏÖWebSocketµÄÉèÖ㬲¢¸½ÉÏÏêϸµÄ´úÂëʾÀý¡£
Ê×ÏÈ£¬ÐèÒªÔÚNginxµÄÉèÖÃÎļþÖÐÔöÌíWebSocketµÄÏà¹ØÉèÖá£
http { ... upstream websocket { server localhost:9001; } ... map $http_upgrade $connection_upgrade { default upgrade; '' close; } ... server { listen 80; server_name example.com; location / { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; } ... } ... }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬ÎÒÃÇÔöÌíÁËÒ»¸öÃûΪ¡°websocket¡±µÄupstream£¬ÓÃÓÚÖ¸¶¨WebSocketµÄÄ¿µÄЧÀÍÆ÷µØµãºÍ¶Ë¿Ú¡£Í¬Ê±£¬Ê¹ÓÃÁËmapÖ¸Á½«$http_upgrade£¨¿Í»§¶ËÉý¼¶ÇëÇóÍ·£©Óë$connection_upgrade£¨nginxµÄÉý¼¶ÇëÇóÍ·£©¾ÙÐÐÁËÓ³Éä¡£ÕâÑù£¬ÔÚ¿Í»§¶ËµÄÉý¼¶ÇëÇóÍ·ÖдøÉÏ¡°Upgrade¡±ºÍ¡°Connection¡±ÕâÁ½¸ö×ֶΣ¬¾Í¿ÉÒÔ´¥·¢Nginx½«HTTPÐÒéÉý¼¶ÖÁWebSocketÐÒ飬´Ó¶øʵÏÖË«ÏòͨѶ¡£
ÔÚserver¿éÖУ¬ÎÒÃÇʹÓÃÁËproxy_passÖ¸Á½«ËùÓÐWebSocketÇëÇó¶¼ÊðÀíµ½websocketÕâ¸öupstreamÖУ¬²¢ÉèÖÃÁËÐÒé°æ±¾ºÍÇëÇóÍ·ÐÅÏ¢¡£ÐèҪעÖصÄÊÇ£¬ÔÚNginxÖоÙÐÐWebSocketµÄÊðÀíʱ£¬±ØÐ轫¡°Upgrade¡±ºÍ¡°Connection¡±ÇëÇóͷһͬ·¢Ë͸øÄ¿µÄЧÀÍÆ÷£¬²»È»ÅþÁ¬½«»á±»¹Ø±Õ£¬Òò´ËÕâÁ½¸öÇëÇóÍ·ÐÅÏ¢±ØÐèͨ¹ýproxy_set_headerÖ¸ÁîÊÖ¶¯Ìí¼Ó¡£
ÁíÍ⣬ÐèҪעÖصÄÊÇ£¬ÔÚÉÏÊöÉèÖÃÖУ¬ÎÒÃǽö½ö¼àÌýÁËHTTP£¨80£©¶Ë¿Ú£¬ÈôÊÇÐèÒªÔÚHTTPSÏÂÉèÖÃWebSocket£¬ÐèÒªÔÚserver¿éÖÐÔöÌíÒÔÏÂÖ¸Á
listen 443 ssl; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem;
µÇ¼ºó¸´ÖÆ
ÒÔÉÏÖ¸ÁîÓÃÓÚ¼àÌýHTTPS£¨443£©¶Ë¿Ú£¬²¢Ö¸¶¨Ö¤ÊéºÍÃÜÔ¿ÎļþµÄ·¾¶ºÍÃû³Æ¡£
ÏÂÃæÊÇÒ»¸öÏêϸµÄWebSocketЧÀÍÆ÷´úÂëʾÀý£¬Ê¹ÓÃNode.jsʵÏÖ£º
const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 9001 }); server.on('connection', (socket, req) => { console.log('Client connected'); socket.on('message', (message) => { console.log(`Received message: ${message}`); socket.send(`Your message: ${message}`); }); socket.on('close', () => { console.log('Client disconnected'); }); });
µÇ¼ºó¸´ÖÆ
¸Ã´úÂëÖУ¬ÎÒÃǽ¨ÉèÁËÒ»¸öWebSocketЧÀÍÆ÷£¬²¢¼àÌýÁË9001¶Ë¿Ú¡£ÔÚÅþÁ¬½¨Éèºó£¬ÎÒÃÇÊä³ö¡°Client connected¡±µÄÐÅÏ¢£¬²¢ÔÚÎüÊÕµ½¿Í»§¶ËµÄÐÂÎź󣬽«¸ÃÐÂÎÅ·µ»Ø¸ø¿Í»§¶Ë£¬È»ºó¼àÌý¹Ø±ÕÊÂÎñ£¬²¢Êä³ö¡°Client disconnected¡±µÄÐÅÏ¢¡£
ͨ¹ýÒÔÉϵĴúÂëºÍÉèÖÃʾÀý£¬ÎÒÃÇ¿ÉÒÔÔÚNginxÖÐʵÏÖWebSocketÐÒéµÄÊðÀíºÍͨѶÊÂÇé¡£ÐèҪעÖصÄÊÇ£¬WebSocketÐÒéµÄʹÓÃÕÕ¾ÉÓÐÒ»¶¨µÄÏÞÖÆ£¬Ïêϸ¶øÑÔ£¬WebSocketÅþÁ¬µÄ½¨ÉèÀú³ÌÓëHTTP/HTTPSÐÒéÀàËÆ£¬¿ÉÊÇ£¬Ò»µ©ÅþÁ¬½¨ÉèÀֳɺó£¬Ë«·½Ö®¼äµÄͨѶÍêÈ«ÒÀÀµÓÚWebSocketÐÒ飬¶ø²»ÔÙÒÀÀµÓÚHTTP/HTTPSÐÒé¡£Òò´Ë£¬ÔÚʹÓÃWebSocketÐÒéʱ£¬ÐèÒª»Ø±ÜһЩͨÀýµÄWeb¿ª·¢ÏÞÖÆ£¬Í¬Ê±£¬Ò²Òª×¢ÖØÇå¾²ÐÔºÍÎȹÌÐԵȷ½ÃæµÄÎÊÌâ¡£
ÒÔÉϾÍÊÇNginxÔõÑùʵÏÖWebSocketÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡