一?什么是websocket
WebSocket協(xié)議相比較于HTTP協(xié)議成功握手后可以多次進(jìn)行通訊,直到連接被關(guān)閉。但是WebSocket中的握手和HTTP中的握手兼容,它使用HTTP中的Upgrade協(xié)議頭將連接從HTTP升級到WebSocket。這使得WebSocket程序可以更容易的使用現(xiàn)已存在的基礎(chǔ)設(shè)施。
WebSocket工作在HTTP的80和443端口并使用前綴ws://或者wss://進(jìn)行協(xié)議標(biāo)注,在建立連接時(shí)使用HTTP/1.1的101狀態(tài)碼進(jìn)行協(xié)議切換,當(dāng)前標(biāo)準(zhǔn)不支持兩個(gè)客戶端之間不借助HTTP直接建立Websocket連接。
二.創(chuàng)建基于Node的WebSocket服務(wù)
安裝node.js和npm
$ yum install nodejs npm
安裝ws和wscat模塊
ws是nodejs的WebSocket實(shí)現(xiàn),我們借助它來搭建簡單的WebSocket Echo Server。
wscat是一個(gè)可執(zhí)行的WebSocket客戶端,用來調(diào)試WebSocket服務(wù)是否正常。
npm install ws wscat
創(chuàng)建一個(gè)簡單的服務(wù)端
$ vim server.jsconsole.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); }); });
運(yùn)行服務(wù)端
$ node server.js Server started
驗(yàn)證服務(wù)端是否正常啟動(dòng)
$ netstat -tlunp|grep 8010tcp6 0 0 :::8010 :::* LISTEN 23864/nodejs
使用wscat做為客戶端測試
wscat命令默認(rèn)安裝當(dāng)前用戶目錄node_modules/wscat/目錄,我這里的位置是/root/node_modules/wscat/bin/wscat
輸入任意內(nèi)容進(jìn)行測試,得到相同返回則說明運(yùn)行正常。
$ cd /root/node_modules/wscat/bin/$ ./wscat --connect ws://127.0.0.1:8010connected (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進(jìn)行反向代理
安裝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;}}}
新聞熱點(diǎn)
疑難解答
圖片精選