Looking for websocket Answers? Try Ask4KnowledgeBase
Looking for websocket Keywords? Try Ask4Keywords

WebSocketsWebSockets入門


備註

本節概述了websocket是什麼,以及開發人員為什麼要使用它。

它還應該提到websocket中的任何大型主題,並鏈接到相關主題。由於websocket的文檔是新的,您可能需要創建這些相關主題的初始版本。

安裝或設置

有關設置或安裝Web套接字的詳細說明。

web-socket客戶端示例

這是javascript中的Web套接字客戶端的示例。
它:

  1. 連接到現場演示服務器。
  2. 發送消息。
  3. 收到消息。
  4. 間隔後斷開連接。
var mySocket    = null;
var serverUrl   = 'wss://echo.websocket.org';  //  wss: is ws: but using SSL.
var oWebSocket  = window.WebSocket || window.MozWebSocket;
if (oWebSocket) {
    mySocket = new oWebSocket (serverUrl);
    if (mySocket) {
        console.log (mySocket);
        mySocket.onopen     = onSocketOpen;
        mySocket.onclose    = onSocketClose;
        mySocket.onmessage  = onSocketMessage;
        mySocket.onerror    = onSocketError;

        setTimeout (closeSocket, 5000);  //  Be polite and free socket when done.
    }
}

function onSocketOpen (evt) {
    console.log ("Socket is now open.");
    mySocket.send ("Hello from my first live web socket!");
}

function onSocketClose (evt) {
    console.log ("Socket is now closed.");
}

function onSocketMessage (evt) {
    console.log ("Recieved from socket: ", evt.data);
}

function onSocketError (evt) {
    console.log ("Error with/from socket!:");
    console.log (evt);
}

function closeSocket () {
    if (mySocket.readyState !== mySocket.CLOSED) {
        console.log ("Closing socket from our end (timer).");
        mySocket.close ();
    }
    else
        console.log ("Socket was already closed (timer).");
}
 

如果您在控制台中運行該代碼,則會得到如下結果:

WebSocket { url: "wss://echo.websocket.org/", readyState: 0, bufferedAmount: 0, onopen: null,
    onerror: null, onclose: null, extensions: "", protocol: "", onmessage: null,
    binaryType: "blob" 
}
2  //  <--- 2 was the socket ID in this instance.
Socket is now open. 
Recieved from socket:  Hello from my first live web socket! 
Closing socket from our end (timer). 
Socket is now closed.