ÔõÑùʹÓÃNginxʵÏÖWebSocketÐÒéÖ§³Ö
ÔõÑùʹÓÃnginxʵÏÖwebsocketÐÒéÖ§³Ö
WebSocketÐÒéÊÇÒ»ÖÖÔÚWebÓ¦ÓóÌÐòÖÐʵÏÖË«ÏòͨѶµÄÐÒ飬ËüÔÊÐíЧÀÍÆ÷×Ô¶¯·¢ËÍÊý¾Ýµ½¿Í»§¶Ë£¬¶ø²»ÐèÒª¿Í»§¶ËÊ×ÏÈÌᳫÇëÇó¡£Ïà±ÈÓڹŰåµÄHTTPÐÒ飬WebSocketÐÒé¾ßÓиüµÍµÄÑӳٺ͸ü¸ßµÄЧÂÊ£¬ÊÊÓÃÓÚʵʱÐÔÒªÇó½Ï¸ßµÄÓ¦Óó¡¾°¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃNginx×÷Ϊ·´ÏòÊðÀíÀ´Ö§³ÖWebSocketÐÒé¡£
NginxÊÇÒ»¸ö¸ßÐÔÄܵĿªÔ´·´ÏòÊðÀíЧÀÍÆ÷£¬¿ÉÒÔÓÃÓÚ¸ºÔØƽºâ¡¢·´ÏòÊðÀí¡¢¾²Ì¬Îļþ»º´æµÈ¶àÖÖ³¡¾°¡£NginxÒ²ÌṩÁËһЩģ¿éºÍÖ¸ÁîÀ´Ö§³ÖWebSocketÐÒé¡£ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄÉèÖÃʾÀý£º
http { # ÆäËûµÄhttpÉèÖà map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; location /ws/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÉèÖÃÖУ¬ÎÒÃǽç˵ÁËÒ»¸ö/ws/·¾¶£¬ÓÃÓÚ´¦ÀíWebSocketµÄÅþÁ¬ÇëÇó¡£WebSocketµÄÇëÇ󽫻ᱻÊðÀíµ½http://backendµØµãÉÏ¡£proxy_passÖ¸ÁîÓÃÓÚÉèÖÃÊðÀíµÄºó¶ËЧÀÍÆ÷µØµã£¬proxy_http_versionÖ¸ÁîÓÃÓÚÉèÖÃÊðÀíµÄHTTPÐÒé°æ±¾¡£proxy_set_headerÖ¸ÁîÓÃÓÚÉèÖÃÇëÇóÍ·ÐÅÏ¢£¬ÆäÖÐUpgradeºÍConnectionÊDZØÐèµÄ£¬ÓÃÓÚ¼û¸æЧÀÍÆ÷¾ÙÐÐÐÒéÉý¼¶¡£
ÐèҪעÖصÄÊÇ£¬ÉÏÊöÉèÖÃÖеÄmapÖ¸ÁîÓÃÓÚ½«¿Í»§¶ËÇëÇóÍ·ÖеÄUpgrade×Ö¶ÎÓ³ÉäΪ$http_upgrade±äÁ¿£¬²¢Æ¾Ö¤ÆäÖµÀ´¶¯Ì¬ÉèÖÃ$connection_upgrade±äÁ¿¡£ÕâÑù¿ÉÒÔʵÏÖÔÚÇëÇóÖз¢Ã÷Upgrade×Ö¶Îʱ£¬½«Upgrade×ֶεÄÖµÉèÖÃΪ$connection_upgrade×ֶεÄÖµ£¬²»È»½«¹Ø±ÕÅþÁ¬¡£
ÔÚÉèÖÃÍê³Éºó£¬ÎÒÃÇÖ»ÐèÒª½«NginxÆô¶¯¼´¿É£º
sudo service nginx start
µÇ¼ºó¸´ÖÆ
ÏÖÔÚ£¬ÎÒÃÇÒѾÍê³ÉÁËʹÓÃNginx×÷Ϊ·´ÏòÊðÀíÀ´Ö§³ÖWebSocketÐÒéµÄÉèÖá£ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëƬ¶ÏÀ´²âÊÔWebSocketµÄÅþÁ¬£º
var socket = new WebSocket("ws://yourdomain.com/ws/"); socket.onopen = function () { console.log("Connection established."); }; socket.onmessage = function (event) { console.log("Received message: ", event.data); }; socket.onclose = function () { console.log("Connection closed."); };
µÇ¼ºó¸´ÖÆ
½«ws://yourdomain.com/ws/Ì滻ΪÏÖʵµÄWebSocketµØµã£¬²¢·¿ªä¯ÀÀÆ÷µÄ¿ª·¢Õß¹¤¾ßÉó²é¿ØÖÆ̨Êä³ö¡£ÈôÊÇÄܹ»Õý³£ÅþÁ¬²¢ÊÕµ½ÐÂÎÅ£¬ÄÇô˵Ã÷WebSocketÐÒéÒѾÀֳɵر»NginxÖ§³Ö¡£
×ÛÉÏËùÊö£¬Í¨¹ýÒÔÉÏÉèÖúʹúÂëʾÀý£¬ÎÒÃÇ¿ÉÒÔÀû±ãµØʹÓÃNginxÀ´Ö§³ÖWebSocketÐÒ飬´Ó¶øʵÏÖʵʱÐÔÒªÇó½Ï¸ßµÄË«ÏòͨѶ¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginxʵÏÖWebSocketÐÒéÖ§³ÖµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡