Nginx·´ÏòÊðÀíWebsocketÉèÖý̳̣¬ÊµÏÖʵʱͨѶ
nginx·´ÏòÊðÀíwebsocketÉèÖý̳̣¬ÊµÏÖʵʱͨѶ
¸ÅÊö:
±¾ÎĽ«ÏÈÈÝÔõÑùͨ¹ýNginxÀ´ÉèÖ÷´ÏòÊðÀíÒÔʵÏÖWebsocketµÄʵʱͨѶ¡£WebsocketÊÇÒ»ÖÖÏÖ´ú»¯µÄÍøÂçͨѶÐÒ飬Äܹ»ÔÚ¿Í»§¶ËºÍЧÀÍÆ÷Ö®¼äʵÏÖÈ«Ë«¹¤µÄʵʱͨѶ¡£
Åä¾°:
ÔڹŰåµÄHTTPÐÒéÖУ¬¿Í»§¶ËÏòЧÀÍÆ÷·¢ËÍÇëÇó£¬Ð§ÀÍÆ÷·µ»ØÏìÓ¦ºóÅþÁ¬Á¬Ã¦¹Ø±Õ£¬ÕâÑùÎÞ·¨ÊµÏÖʵʱͨѶ¡£¶øWebsocketÐÒéÔò½â¾öÁËÕâ¸öÎÊÌ⣬ͨ¹ý½¨Éèºã¾ÃµÄ¡¢Ë«ÏòµÄÅþÁ¬£¬ÊµÏÖÁË¿Í»§¶ËºÍЧÀÍÆ÷Ö®¼äµÄʵʱͨѶ¡£
°ì·¨:
×°ÖÃNginx:
Ê×ÏÈ£¬È·±£ÄúµÄЧÀÍÆ÷ÉÏÒѾװÖÃÁËNginx¡£ÈôÊÇûÓÐ×°Öã¬Çëƾ֤²Ù×÷ϵͳµÄ²î±ð£¬Ê¹ÓÃÏìÓ¦µÄ°ü¹ÜÀí¹¤¾ß¾ÙÐÐ×°Öá£
ÉèÖÃNginx·´ÏòÊðÀí:
·¿ªNginxÉèÖÃÎļþ£¨Í¨³£ÊÇλÓÚ/etc/nginx/nginx.conf£©£¬ÕÒµ½server²¿·Ö£¬Ìí¼ÓÒÔÏÂÉèÖÃ:
server { listen 80; server_name your.domain.com; location /websocket { proxy_pass http://backend_server:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
µÇ¼ºó¸´ÖÆ
ÕâÀォ¿Í»§¶ËÇëÇóµÄ”/websocket”·¾¶ÊðÀíµ½ºó¶ËЧÀÍÆ÷µÄ3000¶Ë¿Ú¡£Í¬Ê±£¬ÉèÖÃUpgradeºÍConnectionÍ·£¬Ê¹NginxÖ§³ÖWebsocketÅþÁ¬¡£
ÇëÈ·±£½«”your.domain.com”Ì滻ΪÄú×Ô¼ºµÄÓòÃû£¬²¢½«”http://backend_server:3000″Ì滻ΪÄú×Ô¼ºµÄºó¶ËЧÀÍÆ÷µØµãºÍ¶Ë¿Ú¡£
ÖØÆôNginx:
ÉúÑÄÉèÖÃÎļþºó£¬Ö´ÐÐÒÔÏÂÏÂÁîÖØÆôNginx£º
sudo service nginx restart
µÇ¼ºó¸´ÖÆ
ÕâÑùNginx¾Í»áƾ֤ÉèÖþÙÐз´ÏòÊðÀí£¬½«WebsocketµÄÇëÇóת·¢µ½ºó¶ËЧÀÍÆ÷ÉÏ¡£
ʾÀý´úÂë:
ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄWebsocketЧÀÍÆ÷µÄʾÀý´úÂ룬ʹÓÃNode.jsºÍws¿â£º
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 3000 }); wss.on('connection', (ws) => { ws.on('message', (message) => { console.log('Received message: ', message); ws.send('Server received: ' + message); }); ws.on('close', () => { console.log('Connection closed'); }); });
µÇ¼ºó¸´ÖÆ
Õâ¸öʾÀý´úÂ뽨ÉèÁËÒ»¸öWebsocketЧÀÍÆ÷£¬¼àÌý3000¶Ë¿Ú£¬µ±Óпͻ§¶ËÅþÁ¬Àֳɺ󣬻á´òÓ¡ÎüÊÕµ½µÄÐÂÎÅ£¬²¢½«»Ø¸´·¢Ëͻؿͻ§¶Ë¡£
²âÊÔ:
ÏÖÔÚ£¬Äú¿ÉÒÔÔÚ¿Í»§¶ËÖн¨ÉèÒ»¸öWebsocketÅþÁ¬£¬ÅþÁ¬µ½NginxÉèÖõÄÓòÃûÉÏ£¬Â·¾¶Îª”/websocket”¡£ÌᳫһÌõÐÂÎź󣬽«»áÎüÊÕµ½Ð§ÀÍÆ÷µÄ»Ø¸´¡£
×ܽá:
ͨ¹ýNginxµÄ·´ÏòÊðÀíÉèÖã¬ÎÒÃÇ¿ÉÒÔÇáËɵؽ«WebsocketµÄÇëÇóת·¢µ½ºó¶ËЧÀÍÆ÷£¬ÊµÏÖʵʱͨѶ¡£ÕâΪ¹¹½¨ÊµÊ±Ó¦ÓÃÌṩÁ˱㵱£¬¾ßÓкܴóµÄÎÞаÐÔºÍÀ©Õ¹ÐÔ¡£
Çë¼ÇµÃÔÚÉú²úÇéÐÎÖаü¹ÜNginxºÍºó¶ËЧÀÍÆ÷µÄÇå¾²ÐԺͿɿ¿ÐÔ£¬²¢°´Ðè¾ÙÐе÷Óźͼà¿Ø¡£Ï£Íû±¾ÎĶÔÄúÃ÷È·ºÍʹÓÃNginx·´ÏòÊðÀíWebsocketÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇNginx·´ÏòÊðÀíWebsocketÉèÖý̳̣¬ÊµÏÖʵʱͨѶµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡