The example snippets in this article are taken from our WebSocket chat client/server sample. See the code, then try out the example for yourself. The example currently has a bug in it; it is trying to use insecure WebSockets but needs to be updated to use a secure one. We will fix this soon!

Creating a WebSocket object

In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server.

The WebSocket constructor accepts one required and one optional parameter:

The URL to which to connect; this should be the URL to which the WebSocket server will respond.

protocolsOptional

Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.

The constructor can throw exceptions:

SECURITY_ERR

The port to which the connection is being attempted is being blocked.

Connection errors

If an error occurs while attempting to connect, first a simple event with the name "error" is sent to the WebSocket object (thereby invoking its onerror handler), and then the CloseEvent is sent to the WebSocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing.

As of Firefox 11 however, it is typical to receive a descriptive error message in the console from the Mozilla platform, and a closing code as defined in RFC 6455, Section 7.4 through the CloseEvent.

Examples

This simple example creates a new WebSocket, connecting to the server at ws://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.

Once the connection is established (that is, readyState is OPEN), exampleSocket.protocol will tell you which protocol the server selected.

In the above examples ws has replaced http, similarly wss replaces https. Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the HTTP server as ws://www.example.com or wss://www.example.com.

Sending data to the server

Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's send() method for each message you want to send:

exampleSocket.send("Here's some text that the server is urgently awaiting!");

Note: Prior to version 11, Firefox only supported sending data as a string.

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen handler to do the work:

Using JSON to transmit objects

One handy thing you can do is use JSON to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:

Closing the connection

When you've finished using the WebSocket connection, call the WebSocket method close():

exampleSocket.close();

It may be helpful to examine the socket's bufferedAmount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network.

Security considerations

WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. In fact, some browsers explicitly forbid this, including Firefox 8 and later.