使用 Nginx 代理 Socket.io/WebSocket 及 负载均衡配置
2019獨角獸企業重金招聘Python工程師標準>>>
轉自:http://naux.me/using-nginx-with-socketio/
0,介紹
Socket.io 一套是基于 WebSocket 協議的實時通訊 API,可以很輕松的開發類似于實時聊天,實時游戲之類的 Web 應用。
Nginx 從 1.3 版本開始支持 WebSocket 代理,我們也能將其應用于 Socket.io,實現如 Socket.io 的負載均衡,和 Web 共用 80(HTTP) 或 443(HTTPS) 端口處理握手請求等需求。
1,配置代理
在?server?配置塊中添加如下配置中的?location /socket.io/?配置塊即可實現 WebSocket 在 80/443 端口握手。
server?{??listen?80;????listen?443?ssl;server_name?example.domain;root?"/project/path";????index?index.html?index.htm?index.php;location?/socket.io/?{????????#?此處改為?socket.io?后端的?ip?和端口即可proxy_pass?http://127.0.0.1:5000;proxy_set_header?Upgrade?$http_upgrade;proxy_set_header?Connection?"upgrade";proxy_http_version?1.1;proxy_set_header?X-Forwarded-For?$proxy_add_x_forwarded_for;proxy_set_header?Host?$host;} }配置中的?/socket.io/?可在 Socket.io 中的?path?選項中配置, 其默認為?/socket.io
2,負載均衡
均衡算法要使用?ip_hash, 防止使用?long-polling?通信時請求分發到了不同的服務器導致異常。
server?{??listen?80;????listen?443?ssl;server_name?example.domain;root?"/project/path";????index?index.html?index.htm?index.php;????//?配置負載的后端upstream?socket_nodes?{ip_hash;server?server1.app:5000?weight=5;server?server2.app:5000;server?server3.app:5000;server?server4.app:5000;}location?/socket.io/?{proxy_pass?http://socket_nodes;proxy_set_header?Upgrade?$http_upgrade;proxy_set_header?Connection?"upgrade";proxy_http_version?1.1;proxy_set_header?X-Forwarded-For?$proxy_add_x_forwarded_for;proxy_set_header?Host?$host;}//?其他配置項//?... }3,測試代碼
寫個小的 Socket.io 代碼測試一下
Node端,開啟一個 Socket.io 服務器,并監聽 5000 端口, 通過上面的 nginx 配置使用 80 端口代理
app.js
var?io?=?require('socket.io').listen(5000);io.sockets.on('connection',?function?(socket)?{??socket.on('set?nickname',?function?(name)?{socket.set('nickname',?name,?function?()?{socket.emit('ready');});});socket.on('msg',?function?()?{socket.get('nickname',?function?(err,?name)?{??????console.log('Chat?message?by?',?name);});}); });客戶端,在瀏覽器中連接 Socket.io 服務器
index.html
<script?src="/socket.io/socket.io.js"></script> <script>var?socket?=?io(); </script>轉載于:https://my.oschina.net/coderman/blog/647897
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的使用 Nginx 代理 Socket.io/WebSocket 及 负载均衡配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL查询 的一些原则
- 下一篇: C#导出EXCEL的几种方法