-
Notifications
You must be signed in to change notification settings - Fork 6
JavaScript WebSocket 101
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")
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() 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).
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);
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;