Websocket

概念:
一種通訊協(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,可看到控制臺相應信息

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 寫作原因:公司這個月的項目計劃是優(yōu)化推送;目前我們推送用的個推(不是不好,項目限制),然后服務器那邊人員忙(本人...
    Thebloodelves閱讀 18,481評論 44 69
  • 很多場景下的應用對數(shù)據(jù)實時更新要求很高。比如股票交易,數(shù)字資產(chǎn)交易,還有一些需要動態(tài)更新數(shù)據(jù)的大屏數(shù)據(jù)可視化應用等...
    前端進階體驗閱讀 1,403評論 0 4
  • Socket并非是一個協(xié)議,而是為了方便使用TCP而抽象出來的一層,是位于應用層和傳輸控制層之間的一組接口。換句話...
    JunChow520閱讀 3,515評論 0 4
  • 原文地址:http://www.ibm.com/developerworks/cn/java/j-lo-WebSo...
    敢夢敢當閱讀 9,027評論 0 50
  • Web領域的實時推送技術,也被稱作Realtime技術。這種技術要達到的目的是讓用戶不需要刷新瀏覽器就可以獲得實時...
    潘良虎閱讀 44,874評論 6 77

友情鏈接更多精彩內(nèi)容