Nginx·´ÏòÊðÀíWebSocketÉèÖã¬ÊµÏÖ¼´Ê±Í¨Ñ¶
nginx·´ÏòÊðÀíwebsocketÉèÖã¬ÊµÏÖ¼´Ê±Í¨Ñ¶
WebSocketÊÇÒ»ÖÖ»ùÓÚTCPÐÒéµÄͨѶÐÒ飬ËüÔÚä¯ÀÀÆ÷ºÍЧÀÍÆ÷Ö®¼ä½¨Éèºã¾ÃµÄË«ÏòÅþÁ¬£¬ÊµÏÖÁËʵʱͨѶµÄ¹¦Ð§¡£Nginx×÷Ϊһ¸ö¸ßÐÔÄܵÄWebЧÀÍÆ÷£¬Ò²¿ÉÒÔͨ¹ý·´ÏòÊðÀíÀ´Ö§³ÖWebSocket£¬²¢ÊµÏֽϺõĸºÔØƽºâºÍ¸ß²¢·¢´¦Àí¡£
Ê×ÏÈ£¬ÔÚNginxÖÐÉèÖ÷´ÏòÊðÀí£¬ÐèÒªÔÚnginx.confÎļþÖÐÌí¼ÓÒ»¶ÎlocationµÄÉèÖ᣼ÙÉèWebSocketЧÀÍÆ÷ÔËÐÐÔÚÍâµØµÄ8000¶Ë¿ÚÉÏ£¬ÎÒÃǽ«Æä·´ÏòÊðÀíµ½NginxЧÀÍÆ÷µÄ3000¶Ë¿ÚÉÏ£¬ÏêϸÉèÖÃÈçÏ£º
server { listen 3000; server_name your.server.name; location / { proxy_pass http://localhost:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÉèÖÃÖУ¬proxy_passÖ¸ÁîÖ¸¶¨ÁËÒª·´ÏòÊðÀíµÄWebSocketЧÀÍÆ÷µÄµØµãºÍ¶Ë¿Ú¡£proxy_http_versionÖ¸¶¨ÁË·´ÏòÊðÀíʹÓõÄHTTP°æ±¾£¬ÕâÀïÉèÖÃΪ1.1¡£proxy_set_header UpgradeºÍproxy_set_header ConnectionÖ¸Áî¸æËßNginxÔÚת·¢WebSocketÇëÇóʱ²»ÒªÐÞ¸ÄUpgradeºÍConnectionÇëÇóÍ·£¬ÒÔ°ü¹ÜWebSocketÅþÁ¬µÄÕý³£½¨Éè¡£
ÐèҪעÖصÄÊÇ£¬ÈôÊÇWebSocketЧÀÍÆ÷ÔËÐÐÔÚHTTPSÐÒéÏ£¬ÐèÒªÔÚÉèÖÃÖÐÌí¼Óproxy_set_header X-Forwarded-Proto $scheme;Ö¸ÁÒÔ¸æËßЧÀÍÆ÷ʹÓÃHTTPSÐÒé¡£
Íê³ÉÒÔÉÏÉèÖúó£¬ÖØмÓÔØNginxÉèÖÃÎļþʹÆäÉúЧ£ºsudo nginx -s reload¡£
½ÓÏÂÀ´£¬ÎÒÃÇ¿ÉÒÔʹÓÃWebSocket¿Í»§¶ËÀ´²âÊÔ·´ÏòÊðÀíÉèÖÃÊÇ·ñÀֳɡ£ÒÔJavaScriptΪÀý£¬´úÂëÈçÏ£º
var socket = new WebSocket('ws://your.server.name/'); socket.onopen = function() { console.log('WebSocketÅþÁ¬Òѽ¨Éè'); }; socket.onmessage = function(event) { console.log('ÊÕµ½ÐÂÎÅ£º' + event.data); }; socket.onclose = function() { console.log('WebSocketÅþÁ¬ÒѹرÕ'); };
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃǽ¨ÉèÁËÒ»¸öWebSocket¹¤¾ß£¬²¢Ö¸¶¨ÁËÒªÅþÁ¬µÄµØµãΪNginxЧÀÍÆ÷µÄµØµã¡£ÔÚonopen¡¢onmessageºÍonclose»Øµ÷º¯ÊýÖУ¬ÎÒÃÇ¿ÉÒÔ´¦ÀíWebSocketÅþÁ¬Àֳɡ¢ÎüÊÕµ½ÐÂÎźÍÅþÁ¬¹Ø±ÕµÄÊÂÎñ¡£
ͨ¹ýÒÔÉÏÉèÖúʹúÂëʾÀý£¬ÎÒÃÇ¿ÉÒÔÔÚNginxÉÏʵÏÖ·´ÏòÊðÀíWebSocket£¬²¢ÊµÏÖ¼´Ê±Í¨Ñ¶µÄ¹¦Ð§¡£Í¨¹ýNginxµÄ¸ßÐÔÄܺ͸ºÔØƽºâ»úÖÆ£¬ÎÒÃÇ¿ÉÒÔΪWebSocketÓ¦ÓÃÌṩÎȹ̿ɿ¿µÄЧÀÍ£¬²¢´¦Àí´ó×Ú²¢·¢ÅþÁ¬¡£Í¬Ê±£¬ÓÉÓÚNginx¾ßÓгÉÊìµÄÔËάºÍ¼à¿Ø¹¤¾ß£¬ÎÒÃÇ¿ÉÒÔÀû±ãµØ¶ÔWebSocketÓ¦ÓþÙÐÐÐÔÄÜÓÅ»¯ºÍ¹ÊÕÏÅŲ顣
×ܽáÆðÀ´£¬Nginx×÷Ϊһ¸öÓÅÒìµÄWebЧÀÍÆ÷£¬Í¨¹ý·´ÏòÊðÀíÉèÖã¬ÎÒÃÇ¿ÉÒÔºÜÀû±ãµØʵÏÖ¶ÔWebSocketµÄÖ§³Ö£¬²¢Ìṩ¸ßÐÔÄܵļ´Ê±Í¨Ñ¶Ð§ÀÍ¡£¹ØÓÚÐèҪʵÏÖ¼´Ê±Í¨Ñ¶¹¦Ð§µÄWebÓ¦ÓÃÀ´Ëµ£¬Nginx·´ÏòÊðÀíÉèÖÃÊÇÒ»¸öÖµµÃ̽Ë÷ºÍʹÓõĽâ¾ö¼Æ»®¡£
ÒÔÉϾÍÊÇNginx·´ÏòÊðÀíWebSocketÉèÖã¬ÊµÏÖ¼´Ê±Í¨Ñ¶µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡