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.