Use WebSockets in JavaScript

2

WebSocket constructor requires a WebSocket URL:

const url = "ws://samblog/chat";
let socket = new WebSocket(url);

Note that if you're on HTTPS page then you have to use TLS version of WebSockets. To do that use wss protocol instead of ws:

const url = "wss://samblog/chat";
let socket = new WebSocket(url);

You should specify what data type you want to use for wrapping incoming binary messages. You should select ArrayBuffer either Blob:

const url = "wss://samblog/chat";
let socket = new WebSocket(url);
socket.binaryType = "arraybuffer";
// socket.binaryType = "blob";

Next, specify event handlers:

socket.onopen = function(event)
{
    console.log("The socket is connected");
};

socket.onclose = function(event)
{
    console.log("The socket is closed");
};

socket.onerror = function(event)
{
    console.error("An error has occurred: " + event);
};

To send messages you should use WebSocket send member function:

socket.send("Text message");

In the example above we send text message. To send a binary message you should pass an object of type ArrayBuffer, ArrayBufferView or Blob into send function.

You don't have to maintain a queue of outgoing message — a web browser will do that for you, so you can call a sequence of send functions and don't have to wait until the data is sent. You can ask how much data is queued for sending by reading bufferedAmount socket property.

And finally, to handle incoming messages you should specify a message handler:

socket.binaryType = "arraybuffer";

socket.onmessage = function(event)
{
    if(event.data instanceof ArrayBuffer)
    {
        // event.data is a binary message
    }
    else
    {
        // event.data is a text message
    }
};
Share this page:

See also how to:

How to display beautiful math formulas on your website with MathJax JavaScript library
How to use NGINX to route HTTP and WebSocket requests
How to use web browser local storage in JavaScript and what you should now about it
How to configure the web-server so you could make cross-domain AJAX-request to it
How to pass messages between different HTML iframes and the main window.