一·什麼是websocket
WebSocket協議相比較於HTTP協議成功握手後可以多次進行通訊,直到連接被關閉。但是WebSocket中的握手和HTTP中的握手兼容,它使用HTTP中的Upgrade協議頭將連接從HTTP升級到WebSocket。這使得WebSocket程序可以更容易的使用現已存在的基礎設施。
WebSocket工作在HTTP的80和443端口並使用前綴ws://
或者wss://
進行協議標註,在建立連接時使用HTTP/1.1的101狀態碼進行協議切換,當前標準不支持兩個客戶端之間不借助HTTP直接建立Websocket連接。
二.創建基於Node的WebSocket服務
安裝node.js和npm
$ yum install nodejs npm
安裝ws和wscat模塊
ws
是nodejs的WebSocket實現,我們藉助它來搭建簡單的WebSocket Echo Server。
wscat
是一個可執行的WebSocket客戶端,用來調試WebSocket服務是否正常。
npm install ws wscat
創建一個簡單的服務端
$ vim server.js console.log("Server started"); var Msg = ''; var WebSocketServer = require('ws').Server , wss = new WebSocketServer({port: 8010}); wss.on('connection', function(ws) { ws.on('message', function(message) { console.log('Received from client: %s', message); ws.send('Server received from client: ' + message); }); });
運行服務端
$ node server.js Server started
驗證服務端是否正常啓動
$ netstat -tlunp|grep 8010 tcp6 0 0 :::8010 :::* LISTEN 23864/nodejs
使用wscat做爲客戶端測試
wscat
命令默認安裝當前用戶目錄node_modules/wscat/
目錄,我這裏的位置是/root/node_modules/wscat/bin/wscat
輸入任意內容進行測試,得到相同返回則說明運行正常。
$ cd /root/node_modules/wscat/bin/ $ ./wscat --connect ws://127.0.0.1:8010 connected (press CTRL+C to quit) > Hello < Server received from client: Hello > Welcome to www.hi-linux.com < Server received from client: Welcome to www.hi-linux.com
三.使用Nginx對WebSocket進行反向代理
安裝Nginx
yum -y install nginx
配置Nginx Websocket
$ vim /usr/local/nginx/conf/nginx.conf # 在http上下文中增加如下配置,確保Nginx能處理正常http請求。 http{ map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream websocket { #ip_hash; server localhost:8010; server localhost:8011; } # 以下配置是在server上下文中添加,location指用於websocket連接的path。 server { listen 80; server_name localhost; access_log /var/log/nginx/yourdomain.log; location / { proxy_pass http://websocket; proxy_read_timeout 300s; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } }
最重要的就是在反向代理的配置中增加了如下兩行,其它的部分和普通的HTTP反向代理沒有任何差別。
proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;
這裏面的關鍵部分在於HTTP的請求中多瞭如下頭部:
Upgrade: websocket Connection: Upgrade
這兩個字段表示請求服務器升級協議爲WebSocket。服務器處理完請求後,響應如下報文# 狀態碼爲101
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: upgrade
告訴客戶端已成功切換協議,升級爲Websocket協議。握手成功之後,服務器端和客戶端便角色對等,就像普通的Socket一樣,能夠雙向通信。不再進行HTTP的交互,而是開始WebSocket的數據幀協議實現數據交換。
這裏使用map
指令可以將變量組合成爲新的變量,會根據客戶端傳來的連接中是否帶有Upgrade頭來決定是否給源站傳遞Connection頭,這樣做的方法比直接全部傳遞upgrade更加優雅。
默認情況下,連接將會在無數據傳輸60秒後關閉,proxy_read_timeout
參數可以延長這個時間或者源站通過定期發送ping幀以保持連接並確認連接是否還在使用。
啓動nginx
/etc/init.d/nginx start
測試通過Nginx訪問WebSocket服務
$ cd /root/node_modules/wscat/bin/ $ ./wscat --connect ws://192.168.2.210 connected (press CTRL+C to quit) > Hello Nginx < Server received from client: Hello Nginx > Welcome to www.hi-linux.com < Server received from client: Welcome to www.hi-linux.com
測試成功,ok