概念:
一種通訊協(xié)議,全雙工模式
客戶端和服務端都可以主動發(fā)送數(shù)據(jù),可以進行實時通訊,持久連接
區(qū)別http協(xié)議:推送模式是定時器Ajax請求,瀏覽器不斷向服務器發(fā)送請求,服務端沒法主動推送,造成數(shù)據(jù)變化更新不及時和寬帶等資源的浪費
其他特點:
- 主動推送的消息可以是文本或者二進制數(shù)據(jù)
- 沒有同源限制,不會出現(xiàn)跨域的問題
- 連接第一階段的握手還是http協(xié)議
- 協(xié)議標識ws,安全加密是wss
如果建立一個websocket連接?
客戶端:
var ws=new WebSocket(url,[protocol])
url是連接的地址,protocol是可接受的子協(xié)議,單個協(xié)議名字字符串或者協(xié)議數(shù)組
url必填,protocol選填
常用方法:
ws.onopen=()=>{
// 向服務器發(fā)送數(shù)據(jù)
ws.send(‘發(fā)送數(shù)據(jù)’)
console.log(‘數(shù)據(jù)發(fā)送...’)
}
ws.onmessage=(e)=>{
var data=e.data
console.log(‘數(shù)據(jù)已接收’)
}
ws.onclose=()=>{
console.log(‘關閉連接’)
}
服務端:(node實現(xiàn))
安裝websocket模塊,npm install websocket
具體測試demo
新建項目文件夾,npm install websocket后出現(xiàn)node_modules依賴
新建index.html如下

圖片1.png
新建index.js代碼如下
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(3000, function() {
console.log((new Date()) + ' Server is listening on port 3000');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
console.log('連接成功')
var connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
setTimeout(()=>{
connection.sendUTF('HI,客戶端');
})
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
console.log('接收到消息')
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
console.log('斷開連接')
});
});
當前項目下命令行啟動node服務,指令為node index.js回車
瀏覽器打開index.html,可看到控制臺相應信息