使用 Nginx 代理 Socket.io/WebSocket 及 负载均衡配置
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
轉(zhuǎn)自:http://naux.me/using-nginx-with-socketio/
0,介紹
Socket.io 一套是基于 WebSocket 協(xié)議的實(shí)時(shí)通訊 API,可以很輕松的開發(fā)類似于實(shí)時(shí)聊天,實(shí)時(shí)游戲之類的 Web 應(yīng)用。
Nginx 從 1.3 版本開始支持 WebSocket 代理,我們也能將其應(yīng)用于 Socket.io,實(shí)現(xiàn)如 Socket.io 的負(fù)載均衡,和 Web 共用 80(HTTP) 或 443(HTTPS) 端口處理握手請(qǐng)求等需求。
1,配置代理
在?server?配置塊中添加如下配置中的?location /socket.io/?配置塊即可實(shí)現(xiàn) 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?選項(xiàng)中配置, 其默認(rèn)為?/socket.io
2,負(fù)載均衡
均衡算法要使用?ip_hash, 防止使用?long-polling?通信時(shí)請(qǐng)求分發(fā)到了不同的服務(wù)器導(dǎo)致異常。
server?{??listen?80;????listen?443?ssl;server_name?example.domain;root?"/project/path";????index?index.html?index.htm?index.php;????//?配置負(fù)載的后端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;}//?其他配置項(xiàng)//?... }3,測(cè)試代碼
寫個(gè)小的 Socket.io 代碼測(cè)試一下
Node端,開啟一個(gè) Socket.io 服務(wù)器,并監(jiān)聽 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 服務(wù)器
index.html
<script?src="/socket.io/socket.io.js"></script> <script>var?socket?=?io(); </script>轉(zhuǎn)載于:https://my.oschina.net/coderman/blog/647897
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的使用 Nginx 代理 Socket.io/WebSocket 及 负载均衡配置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL查询 的一些原则
- 下一篇: 通过Nginx,Tomcat访问日志(a