×ðÁú¿­Ê±

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ÉèÖã¬ÊµÏÖ¼´Ê±Í¨Ñ¶µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±ÊµÊ±ÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
¡¾ÍøÕ¾µØͼ¡¿¡¾sitemap¡¿