Using Native WebSockets in the Browser

The native WebSocket API available in supported browsers is quite small and clean, but it doesn’t do a lot other than send text to and from the server, so the addition of compatibility and fallback issues make it a chore to work with directly.

Assuming you have a server that supports WebSockets, you can open a connection using a new WebSocket object from the browser with the following:

    var socket = new WebSocket("ws://servername.com/socket-resource");

The WebSocket equivalent of the http:// URL prefix is ws://. Secure WebSockets, the equivalent of https://, has a wss:// prefix.

That socket object has four callbacks used to listen for events on the socket:

socket.onopen = function(){
  // Socket has been opened
}; 
socket.onmessage = function(event) {
  // Message data in event.data
};
socket.onclose = function() {
  // WebSocket has been closed
};
socket.onerror = function(event) {
  // Error triggered
};

To send data on the socket, call socket.send:

socket.send(message);

This sends the message string to the server. One thing to remember with WebSockets is that all the data sent back and forth is in the form of a string, so it’s up to you to encode and decode those strings with some mechanism. (JSON is an obvious and popular choice.)

Rather than set up a server simply to test out native WebSockets, the websocket.org website provides an echo server you can use to test writing the client-side WebSocket code.

Create a new file called echo.html and add ...

Get Professional HTML5 Mobile Game Development 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.