websocket 實(shí)現(xiàn)前端通訊實(shí)戰(zhàn)

本文介紹websocket實(shí)現(xiàn)前端通訊
要實(shí)現(xiàn)通訊需要連接、發(fā)送、接收以及需要websocket服務(wù)器

我們來看一個簡單的websocket demo

  var socket = new WebSocket('ws://localhost:8080/');
  socket.onopen = function () {
      console.log('Connected!');
  };
  socket.onmessage = function (event) {
      console.log('Received data: ' + event.data);
      socket.close();
  };
  socket.onclose = function () {
      console.log('Lost connection!');
  };
  socket.onerror = function () {
      console.log('Error!');
  };
  socket.send('hello, world!');

可以說上面就是一個健全的websocket 通信了. 我們需要創(chuàng)建一個WebSocket對象, 里面的參數(shù)指定連接的路由. 而且,他也是事件驅(qū)動的.常見的事件監(jiān)聽有.

event effect
open 當(dāng)ws連接建立時觸發(fā)
message 當(dāng)有信息到來時觸發(fā)
error 當(dāng)連接發(fā)生錯誤時觸發(fā)
close 當(dāng)連接斷開時觸發(fā)

websocket 發(fā)送數(shù)據(jù)
另外,websocket 最大的特點(diǎn)就是可以雙向通信。這里可以使用.ws.send()
方法發(fā)送數(shù)據(jù), 不過只能發(fā)送String和二進(jìn)制. 這里,我們通常call 數(shù)據(jù)叫做 Frames
. 他是數(shù)據(jù)發(fā)送的最小單元.包含數(shù)據(jù)的長度和數(shù)據(jù)內(nèi)容.下面就是幾種常用的發(fā)送方式

 socket.send("Hello server!"); 
 socket.send(JSON.stringify({'msg': 'payload'})); 

  var buffer = new ArrayBuffer(128);
  socket.send(buffer); 

  var intview = new Uint32Array(buffer);
  socket.send(intview); 

  var blob = new Blob([buffer]);
  socket.send(blob);

另外還可以使用binaryType指定傳輸?shù)臄?shù)據(jù)格式,不過一般都用不上,就不說了.不過需要提醒的是, send方法,一般在open和message的回調(diào)函數(shù)中調(diào)用.

websocket 接受數(shù)據(jù)
同理,和SSE差不多, 通過監(jiān)聽message事件,來接受server發(fā)送回來的數(shù)據(jù). 接受其實(shí)就是通過event.data
來獲取. 不過, 需要和server端商量好data的類型.

ws.onmessage = function(msg) { 
  if(msg.data instanceof Blob) { 
    processBlob(msg.data);
  } else {
    processText(JSON.parse(msg.data)); //接受JSON數(shù)據(jù)
  }
}

那server端應(yīng)該怎樣處理websocket通信呢? websocket雖然是另外一種協(xié)議,不過底層還是封裝了TCP通信, 所以使用nodeJS的net模塊,基本就可以滿足,不過里面需要設(shè)置很多的頭. 這里推薦使用ws模塊.
NodeJS 發(fā)送websocket數(shù)據(jù)
簡單的websocket demo

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({ port: 8080 });

//通過ws+ssl的方式通信. 和HTTPS類似
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

具體代碼示例:

html

<div id="page-wrapper">
  <h1>WebSockets Demo</h1>
  
  <div id="status">Connecting...</div>
  
  <ul id="messages"></ul>
  
  <form id="message-form" action="#" method="post">
    <textarea id="message" placeholder="Write your message here..." required></textarea>
    <button type="submit">Send Message</button>
    <button type="button" id="close">Close Connection</button>
  </form>
</div>

css

*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
  background: #333;
}

#page-wrapper {
  width: 650px;
  background: #FFF;
  padding: 1em;
  margin: 1em auto;
  border-top: 5px solid #69c773;
  box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}

h1 {
    margin-top: 0;
}

#status {
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.open {
  color: green;
}

.closed {
  color: red;
}


ul {
  list-style: none;
  margin: 0;
  padding: 0;
  font-size: 0.95rem;
}

ul li {
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid #EEE;
}

ul li:first-child {
  border-top: 1px solid #EEE;
}

ul li span {
  display: inline-block;
  width: 90px;
  font-weight: bold;
  color: #999;
  font-size: 0.7rem;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.sent {
  background-color: #F7F7F7;
}

.received {}

#message-form {
  margin-top: 1.5rem;
}

textarea {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  border: 1px solid #D9D9D9;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
  min-height: 100px;
  margin-bottom: 1rem;
}

button {
  display: inline-block;
  border-radius: 3px;
  border: none;
  font-size: 0.9rem;
  padding: 0.6rem 1em;
  color: white;
  margin: 0 0.25rem;
  text-align: center;
  background: #BABABA;
  border-bottom: 1px solid #999;
}

button[type="submit"] {
  background: #86b32d;
  border-bottom: 1px solid #5d7d1f;
}

button:hover {
  opacity: 0.75;
  cursor: pointer;
}

JS

window.onload = function() {

  // Get references to elements on the page.
  var form = document.getElementById('message-form');
  var messageField = document.getElementById('message');
  var messagesList = document.getElementById('messages');
  var socketStatus = document.getElementById('status');
  var closeBtn = document.getElementById('close');


  // Create a new WebSocket.
  var socket = new WebSocket('ws://echo.websocket.org');


  // Handle any errors that occur.
  socket.onerror = function(error) {
    console.log('WebSocket Error: ' + error);
  };


  // Show a connected message when the WebSocket is opened.
  socket.onopen = function(event) {
    socketStatus.innerHTML = 'Connected to: ws://echo.websocket.org';
    socketStatus.className = 'open';
  };


  // Handle messages sent by the server.
  socket.onmessage = function(event) {
    var message = event.data;
    messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
                               message + '</li>';
  };


  // Show a disconnected message when the WebSocket is closed.
  socket.onclose = function(event) {
    socketStatus.innerHTML = 'Disconnected from WebSocket.';
    socketStatus.className = 'closed';
  };


  // Send a message when the form is submitted.
  form.onsubmit = function(e) {
    e.preventDefault();

    // Retrieve the message from the textarea.
    var message = messageField.value;

    // Send the message through the WebSocket.
    socket.send(message);

    // Add the message to the messages list.
    messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
                              '</li>';

    // Clear out the message field.
    messageField.value = '';

    return false;
  };


  // Close the WebSocket connection when the close button is clicked.
  closeBtn.onclick = function(e) {
    e.preventDefault();

    // Close the WebSocket.
    socket.close();

    return false;
  };

};

歡迎加qq群交流:610334712
websocket知識:xxxx連接
nodejs服務(wù)端信息:xxxx連接
參考及更多ajax、JSOP、SSE實(shí)現(xiàn)前端通訊請閱讀
https://segmentfault.com/a/1190000004682473#articleHeader8

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

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

  • 1. 前言 Web端即時通訊技術(shù)因受限于瀏覽器的設(shè)計(jì)限制,一直以來實(shí)現(xiàn)起來并不容易,主流的Web端即時通訊方案大致...
    零一間閱讀 871評論 0 2
  • 【執(zhí)子之手】2017年11月24日 璨璨+Tina 小小書語者 Day18 1、中午看了小熊寶寶繪本刷牙、收起來,...
    cancan媽閱讀 204評論 0 0
  • 山村有一愚漢,大伙叫他蠻牛。他身材瘦小,皮膚黝黑,滿臉胡子拉茬,說起話來怪聲怪氣,常年穿著一雙黃膠鞋。 蠻牛自幼喪...
    劍行天下閱讀 721評論 1 7
  • 粵港澳青年作家創(chuàng)作學(xué)會詩詞選 七言絕句 押東韻 一派英姿別樣紅,高冠豪氣戲春風(fēng)。 壯夫歃血染南粵,欲與天公較俊雄。
    粵北雄鷹閱讀 1,774評論 28 55
  • 關(guān)于章節(jié)標(biāo)題,主要是以下形式:章節(jié)號+章節(jié)名稱+主視角人物+章節(jié)發(fā)生的年份 以第一部第一章為例:第1部 第1章 “...
    惡人CC閱讀 291評論 0 0

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