CREATE A WEBSOCKET CLIENT

To connect to a WebSocket service running on a web server, you will need to create a WebSocket client that runs on the user’s web browser that supports the WebSockets API.

Before initializing a connection, you will need to verify if the browser supports the WebSocket API by testing for the window.WebSocket object. If it exists, you can establish the connection to a WebSocket service using a ws://hostname/path URL:

if ( 'WebSocket' in window ) {
   var websocket = new WebSocket(wsURL);

The returned object is then used to register an event listener for each of the four event types, open, close, message, and error:

websocket.addEventListener(eventtype, function, false);

Each event handler function will receive an ...

Get HTML5: Your visual blueprint™ for designing rich web pages and applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.