WebSocket Tutorial

By Xah Lee. Date: . Last updated: .

WebSocket allows 2-way communication between browser and server, on a open channel over TCP. As of 2016, all browsers supports it.

The advantage of WebSocket over HTTP is that client and server can send/receive data any time in both directions at the same time (called full duplex), without overhead of reconnection, and no need for periodic push/pull/polling to check for availability of data.

For WebSocket to work, the server needs to support the WebSocket protocol.

The client, can use WebSocket API by JavaScript via browser.

Create a Socket

// create a socket
const mySocket = new WebSocket("ws://ws.example.com:80/xyz/");

WebSocket protocol URL starts with:

WebSocket use the same default port as HTTP, port 80, if not specified.

Set Up Basic Event Handlers

// setup socket event handlers

mySocket.onopen = function(e) {
    // socket is now connected
};

mySocket.onclose = function(e) {
    // socket closed
};

mySocket.onerror = function(e) {
    // something's wrong
};

Send a Message

// send message
mySocket.send("good morn");

Receive Message

Messages are received as a event.

// setup a event handler for incoming message
mySocket.onmessage = function(e) {
    const message = e.data;
    console.log(message);
};

The function will receive a argument that's MessageEvent object.

The object has a property key "data", which holds the actual message.

Close Connection

mySocket.close();

readyState Property

The property readyState holds a value that indicates the socket readiness.

The value is a integer.

WebSocket Binary Data or Array Buffer

WebSocket can transmit binary data, or array buffer.

// send binary data,
mySocket.binaryType = "blob";
// send array buffer
mySocket.binaryType = "arraybuffer";

you will need to construct the blob or arraybuffer before sending.

Sample WebSocket Based Chat Client

<!-- The chat UI is just a single, wide text input field -->
<!-- New chat messages will be inserted before this element -->
<input id="input" style="width:100%"/>
// sample WebSocket based chat client, from https://github.com/davidflanagan/javascript6_examples/blob/master/examples/22.16.wschatclient.html

window.onload = function() {
    // Take care of some UI details
    var nick = prompt("Enter your nickname");
    var input = document.getElementById("input");
    input.focus(); // Set keyboard focus

    // Open a WebSocket
    var socket = new WebSocket("ws://" + location.host + "/");

    // handle receive message from the server
    socket.onmessage = function(event) {
        var msg = event.data;
        var node = document.createTextNode(msg);
        var div = document.createElement("div");
        div.appendChild(node);
        document.body.insertBefore(div, input);
        input.scrollIntoView();
    }

    // send message to server, when user press return
    input.onchange = function() {
        var msg = nick + ": " + input.value;
        socket.send(msg);
        input.value = "";
    }
};