×ðÁú¿­Ê±

Nginx·´ÏòÊðÀíWebsocketÉèÖÃ½Ì³Ì £¬ÊµÏÖʵʱͨѶ

nginx·´ÏòÊðÀíwebsocketÉèÖÃ½Ì³Ì £¬ÊµÏÖʵʱͨѶ

Websocket ÊÇÒ»ÖÖ»ùÓÚ³¤ÅþÁ¬µÄЭÒé £¬¿ÉÒÔʵÏÖʵʱͨѶ £¬ÍŽá Nginx ·´ÏòÊðÀíµÄ¹¦Ð§ £¬¿ÉÒÔ¸üºÃµØÖÎÀíºÍ·Ö·¢ Websocket ÇëÇó¡£±¾ÎĽ«ÏÈÈÝÔõÑùÉèÖà Nginx ·´ÏòÊðÀíÀ´ÊµÏÖ Websocket ʵʱͨѶ¡£

È·ÈÏ Nginx ÒÑ×°ÖÃ

Ê×ÏÈ £¬È·±£ÒѾ­ÔÚЧÀÍÆ÷ÉÏ×°ÖÃÁË Nginx¡£ÈôÊÇûÓÐ×°Öà £¬¿ÉÒÔʹÓÃÒÔÏÂÏÂÁî×°Öãº

sudo apt-get update
sudo apt-get install nginx

µÇ¼ºó¸´ÖÆ

ÐÞ¸Ä Nginx ÉèÖÃÎļþ

ʹÓÃÎı¾±à¼­Æ÷·­¿ª Nginx µÄÉèÖÃÎļþ £¬Ò»Ñùƽ³£Î»ÓÚ /etc/nginx/nginx.conf »ò /etc/nginx/conf.d/default.conf¡£Æ¾Ö¤ÏÂÃæµÄʾÀý¾ÙÐÐÐ޸ģº

server {
listen 80;
server_name yourdomain.com;

location /websocket {
   proxy_pass http://backend;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "Upgrade";
}
}

µÇ¼ºó¸´ÖÆ

ÔÚÉÏÊöÉèÖÃÖÐ £¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪ websocket µÄλÖã¨location£© £¬²¢½«ÇëÇóÊðÀíµ½ÃûΪ backend µÄºó¶ËЧÀÍÆ÷¡£×¢ÖØ yourdomain.com ºÍ backend Ó¦¸ÃÌ滻ΪÄã×Ô¼ºµÄÓòÃûºÍºó¶ËЧÀÍÆ÷µØµã¡£

±ðµÄ £¬ÎÒÃÇ»¹ÉèÖÃÁËÁ½¸öÊðÀíÇëÇóÍ· Upgrade ºÍ Connection £¬ÕâÊÇΪÁËʹ Nginx Äܹ»×¼È·´¦Öóͷ£ Websocket ÅþÁ¬¡£

ÖØÆô Nginx

Íê³ÉÉèÖÃÎļþµÄÐ޸ĺó £¬ÉúÑIJ¢Í˳öÎı¾±à¼­Æ÷¡£È»ºóʹÓÃÒÔÏÂÏÂÁîÖØÆô Nginx£º

sudo service nginx restart

µÇ¼ºó¸´ÖÆ

²âÊÔWebsocketÅþÁ¬

ÏÖÔÚÄã¿ÉÒÔʹÓÃÈκÎÖ§³Ö Websocket ЭÒéµÄ¿Í»§¶ËÓ¦ÓóÌÐò£¨Èçä¯ÀÀÆ÷»òÖն˹¤¾ß£©À´²âÊÔÄãµÄ Websocket ЧÀÍÆ÷¡£¼ÙÉèÄãµÄÓòÃûÊÇ yourdomain.com £¬Ê¹ÓÃÒÔÏ´úÂë¾ÙÐвâÊÔ£º

const socket = new WebSocket('ws://yourdomain.com/websocket');

socket.onopen = () => {
   console.log('ÅþÁ¬Òѽ¨Éè');
};

socket.onmessage = (event) => {
   console.log('ÊÕµ½ÐÂÎÅ:', event.data);
};

socket.onclose = () => {
   console.log('ÅþÁ¬ÒѹرÕ');
};

socket.onerror = (error) => {
   console.error('±¬·¢¹ýʧ:', error);
};

µÇ¼ºó¸´ÖÆ

½«ÉÏÊö´úÂëÕ³Ìùµ½Ò»¸öÖ§³Ö JavaScript µÄÇéÐÎÖÐÔËÐÐ £¬Èçä¯ÀÀÆ÷µÄ¿ª·¢Õß¹¤¾ß¿ØÖÆ̨ £¬»òʹÓà Node.js ÔËÐС£ÈôÊÇÄãÄÜ¿´µ½ÅþÁ¬Òѽ¨ÉèµÄÈÕÖ¾ £¬ËµÃ÷ÄãµÄ Nginx ÉèÖÃºÍ Websocket ЧÀÍÆ÷¶¼Õý³£ÊÂÇé¡£

×ܽá

ͨ¹ý Nginx ·´ÏòÊðÀíµÄÉèÖà £¬ÎÒÃÇ¿ÉÒÔ½« Websocket ÇëÇóÊðÀíµ½ºó¶ËЧÀÍÆ÷ £¬´Ó¶øʵÏÖʵʱͨѶµÄ¹¦Ð§¡£±¾ÎÄÏÈÈÝÁËÔõÑùÉèÖà Nginx £¬È»ºóʹÓà JavaScript ´úÂë¶Ô Websocket ÅþÁ¬¾ÙÐвâÊÔ¡£Ï£ÍûÕâƪÎÄÕ¶ÔÄãÃ÷È·ºÍÓ¦Óà Nginx ·´ÏòÊðÀí Websocket ÓÐËù×ÊÖú¡£

ÒÔÉϾÍÊÇNginx·´ÏòÊðÀíWebsocketÉèÖÃ½Ì³Ì £¬ÊµÏÖʵʱͨѶµÄÏêϸÄÚÈÝ £¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

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

Ïà¹ØÐÂÎÅ

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

13452372176

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

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

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