An Introduction To WebSockets

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

WebSocket Events

Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above −
open:
Socket.onopen
    This event occurs when socket connection is established.
message:
  Socket.onmessage
            This event occurs when client receives data from server.
error:
  Socket.onerror
            This event occurs when there is any error in communication.
close:
Socket.onclose
      This event occurs when connection is closed.

WebSocket Methods

Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above −

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

Socket.close()
The close() method would be used to terminate any existing connection.
if ("WebSocket" in window)
{
    WebSocket = new WebSocket("wss://echo.websocket.org");
    WebSocket.onopen = function (Event)
    {
        //Web Socket Connected Successfully";
        WebSocket.send("Message to send");
    };
    WebSocket.onmessage = function (Event)
    {
        //Message is received...
    };

    WebSocket.onclose = function (event)
    {
        //Web Socket Closed Successfully
    };

    WebSocket.onerror = function (Error)
    {
        //Web Socket Error
    };
}
else
{
    //Web Socket Error: NOT supported by your Browser!
}

No comments:

Post a Comment