Menu

HTML5 TUTORIALS - HTML5 WebSocket

HTML5 WebSocket

ADVERTISEMENTS


var Socket = new WebSocket(url, [protocal] );

ADVERTISEMENTS

AttributeDescription
Socket.readyState

The readonly attribute readyState represents the state of the connection. It can have the following values:

  1. A value of 0 indicates that the connection has not yet been established.

  2. A value of 1 indicates that the connection is established and communication is possible.

  3. A value of 2 indicates that the connection is going through the closing handshake.

  4. A value of 3 indicates that the connection has been closed or could not be opened.

Socket.bufferedAmount

The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method.

ADVERTISEMENTS

EventEvent HandlerDescription
openSocket.onopenThis event occurs when socket connection is established.
messageSocket.onmessageThis event occurs when client receives data from server.
errorSocket.onerrorThis event occurs when there is any error in communication.
closeSocket.oncloseThis event occurs when connection is closed.

MethodDescription
Socket.send()

The send(data) method transmits data using the connection.

Socket.close()

The close() method would be used to terminate any existing connection.

Client Side HTML & JavaScript Code:


<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://localhost:9998/echo");
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>

Start the Server


$sudo python standalone.py -p 9998 -w ../example/