WebSocket簡單使用(二) – 用戶端

來源:互聯網
上載者:User

原文 http://www.oseye.net/user/kevin/blog/79

關於WebSocket我打算分如下幾篇博文來探探路:

  1. WebSocket簡單使用(一) - 概念
  2. WebSocket簡單使用(二) - 用戶端
  3. WebSocket簡單使用(三) - 伺服器端
  4. WebSocket簡單使用(四) - 完整執行個體
  5. WebSocket簡單使用(五) - 類比 串連鍵盤 功能

背景:

前幾天老大突然發現有個連結鍵盤的功能,我仔細想了下或許是使用WebSocket來實現的,又加上最近HTML5的呼聲愈來愈高,覺得有必要研究下HTML5了。

如概念篇中介紹的握手協議,用戶端是由瀏覽器提供了API,所以只要使用JavaScript來簡單調用即可,而伺服器端是要自己實現的,伺服器端將在下個博文來講。

WebSocket JavaScript 介面定義:

  1. [Constructor(inDOMString url, optional inDOMString protocol)]
  2. interfaceWebSocket{
  3. readonly attribute DOMString URL;
  4. // ready state
  5. constunsignedshort CONNECTING =0;
  6. constunsignedshort OPEN =1;
  7. constunsignedshort CLOSED =2;
  8. readonly attribute unsignedshort readyState;
  9. readonly attribute unsignedlong bufferedAmount;
  10.  
  11. // networking
  12. attribute Function onopen;
  13. attribute Function onmessage;
  14. attribute Function onclose;
  15. boolean send(inDOMString data);
  16. void close();
  17. };
  18. WebSocketimplementsEventTarget;

簡單瞭解下介面方法和屬性:

  • readyState表示串連有四種狀態:
    CONNECTING (0):表示還沒建立串連;
    OPEN (1): 已經建立串連,可以進行通訊;
    CLOSING (2):通過關閉握手,正在關閉串連;
    CLOSED (3):串連已經關閉或無法開啟;
  • url是代表 WebSocket 伺服器的網路地址,協議通常是”ws”或“wss(加密通訊)”,send 方法就是發送資料到伺服器端;
  • close 方法就是關閉串連;
  • onopen串連建立,即握手成功觸發的事件;
  • onmessage收到伺服器訊息時觸發的事件;
  • onerror異常觸發的事件;
  • onclose關閉串連觸發的事件;

JavaScript呼叫瀏覽器介面執行個體如下:

    1. var wsServer ='ws://localhost:8888/Demo';//伺服器位址
    2. var websocket =newWebSocket(wsServer);//建立WebSocket對象
    3. websocket.send("hello");//向伺服器發送訊息
    4. alert(websocket.readyState);//查看websocket目前狀態
    5. websocket.onopen =function(evt){
    6. //已經建立串連
    7. };
    8. websocket.onclose =function(evt){
    9. //已經關閉串連
    10. };
    11. websocket.onmessage =function(evt){
    12. //收到伺服器訊息,使用evt.data提取
    13. };
    14. websocket.onerror =function(evt){
    15. //產生異常
    16. };

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.