以爲很容易用到.. Nginx 從 1.3 開始支持 WebSocket, 如今已是 1.4.4 了
相對 HTTP, 看過例子發現配置其實比較簡單,html
先用 ws
模塊寫一個簡單的 WebSocket 服務器:node
Server = require('ws').Server wss = new Server port: 3000 wss.on 'connection', (ws) -> console.log 'a connection' ws.send 'started' console.log 'server started'
而後修改 Hosts, 添加, 好比 ws.repo
, 指向 127.0.0.1
而後是 Nginx 配置:nginx
server { listen 80; server_name ws.repo; location / { proxy_pass http://127.0.0.1:3000/; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
Reload Nginx 而後從瀏覽器控制檯嘗試連接, OKgit
new WebSocket('ws://ws.repo/')
或者經過 Upstream 的寫法:github
upstream ws_server { server 127.0.0.1:3000; } server { listen 80; server_name ws.repo; location / { proxy_pass http://ws_server/; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
WebSocket 先是經過 HTTP 創建鏈接,
而後經過 101 狀態碼, 表示切換協議,, 在配置裏是 Upgrade
不清楚具體裏邊發生了什麼... 求指點...web
具體 HTTP Header 上的參數參考 SegmengFault 上的文章:
http://segmentfault.com/a/1190000000382788segmentfault
參考的相關文章:
nginx and WebSockets
WebSocket connection failed with nginx, nodejs and socket.io
Proxying WebSockets with Nginx
zhangkaitao/websocket-protocol
細說WebSocket - Node篇瀏覽器
返回博客首頁: http://blog.tiye.me服務器