This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

websocket API


WebSocket is a JavaScript API and accompanying protocol that allows you to create "web sockets", capable of bi-directional full-duplex communication over a persistent TCP connection (socket).

Object representing the close event for a WebSocket.
WebSocket Object API Details
Object for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.


 Writing a WebSocket application in JavaScript is quite simple. Establish a connection, and hook into the open, error, message and close events as necessary. Remember, WebSocket is subject to the same-origin policy, like AJAX. This means if you want to test your client locally, you'll need to run a web server (e.g., python -m SimpleHTTPServer or php -S localhost:8000). Here's a simple example client that should work in newer browsers:
  var socket = new WebSocket('ws://localhost:8080/');
  socket.onopen = function () {
  socket.onmessage = function (event) {
      console.log('Received data: ' +;
  socket.onclose = function () {
      console.log('Lost connection!');
  socket.onerror = function () {
  socket.send('hello, world!');

And to complement it, here’s an example echo server in Python using Twisted:

  from twisted.internet import protocol, reactor
  from txws import WebSocketFactory

  class Echo(protocol.Protocol):
      def dataReceived(self, data):

  class EchoFactory(protocol.Factory):
      def buildProtocol(self, addr):
          return Echo()

  reactor.listenTCP(8080, WebSocketFactory(EchoFactory()))


Like standard HTTP, WebSocket by default uses port 80 in the clear and 443 over SSL. The WebSocket client establishes an HTTP connection and requests to switch the protocol using the HTTP Upgrade mechanism, and then follows a handshake protocol to ensure both client and server support WebSocket. Because WebSocket connections start off as HTTP, WebSocket can work through many existing proxies and firewalls, unlike some other protocols.

Once the connection is established, messages are sent as "frames", in either text or binary format, in both directions. These are the data strings you send and receive in JavaScript.

WebSocket URIs have the same basic format as HTTP URIs, but with a different URI scheme: ws://hostname:port/path, e.g. ws:// or ws:// The path can be used to distinguish the purpose of the connection; however, some servers ignore it. Secure WebSocket (WebSocket over SSL/TLS) URIs begin with wss:// instead of ws://.

See also

External resources