Skip to content

JavaScript WebSocket 101

Igal edited this page Apr 9, 2017 · 5 revisions

WebSocket Browser Support

WebSockets are supported for about 94% of Web users at the time of this writing (meaning that it might be even more by the time you read this). To see browser support for WebSocket please visit Can I Use > WebSockets

You can check that the current browser supports WebSockets by testing "WebSocket" in window, which is akin to the cfscript statement window.keyExists("WebSocket")

Armed with that information, you can let the user know if her browser does not support WebSockets:

if (!("WebSocket" in window))
    alert("Sorry, but this Web browser does not support WebSockets. #dinosaur");

The Simple Way to Create a WebSocket

The idea is simple: create a new WebSocket object by passing the server endpoint, configure event handlers for the events that you want to... well... handle (i.e. onopen, onmessage, onerror, and onclose), and use its methods like send(message) to interact with the server:

var wsecho = new WebSocket("ws://localhost:8080/ws/echo");

Now you have a WebSocket client instance named wsecho which you can use to send and receive messages (assuming that the server was configured properly for this endpoint and has accepted the connection, of course).

A Better Way to Create a WebSocket

When you create a WebSocket on a page that was loaded with a secure protocol, i.e. https, you must use the secure WebSocket protocol wss. You can construct the URL as follows:

var endpoint = "/ws/echo";
var protocol = (document.location.protocol == "https:") ? "wss://" : "ws://";
var url = protocol + document.location.host + endpoint;

var wsecho = new WebSocket(url);

Configuring WebSocket Event Handlers

Now that you have a WebSocket client, configure event handlers. For the sake of simplicity, in this example I will just dump the Event argument to the JavaScript console via console.log, but in your application you should of course do something more useful with it, like inspect the event properties and update the UI.

var log = function(evt){ console.log(evt); }
wsecho.onopen    = log;
wsecho.onmessage = log;
wsecho.onerror   = log;
wsecho.onclose   = log;

Using the WebSocket Object

Using the WebSocket object is very straightforward. You can call its methods like send(message) or close(), or inspect its properties like readyState. For example:

if (wsecho.readState == WebSocket.OPEN)
    wsecho.send("Hello Lucee!");

Keep in mind that navigating out of the page, including reloading the page, will destroy the JavaScript environment including the WebSocket object that you created.

More Information

Clone this wiki locally