WebSocket

A web technology that provides full-duplex communications over a single TCP connection


WebSocket Test

This test sends a message to "ws://echo.websocket.org/" endpoint and gets an echo back.


    WebSocket protocol communications typically use TCP port number 80, so environments that block non-standard Internet connections by using a firewall will still pass WebSocket packets.

    Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as a request to switch to WebSocket protocol. Each frame of WebSocket protocol has only 2 bytes of overhead, and there are no headers.

    Whereas an HTTP URL begins with http:// or https:// for secure HTTP, the WebSocket URL begins with ws:// or wss:// for secure WebSocket protocol.


    There is no native support for web farm load balancing with WebSocket protocol and the WebSocket object.
    When there are multiple web servers, you can implement sticky servers. You can share state across web servers by using one of the many products that handle this such as Redis and the Microsoft App Fabric Caching Service.

    Code Example

    There is no open method on the WebSocket object. When you instantiate the WebSocket object, it automatically attempts to open asynchronously.

    var webSocket;
    
    $(function(){
        if(IsWebSocketSupported()){
            Connect();
            $("#btnSend").on("click", DoSend);
        }
    });
    
    function IsWebSocketSupported() {
        if (window.WebSocket) {
            console.log("WebSocket is supported.");
            return true;
        } else {
            console.log("WebSocket is NOT supported");
            return false;
        }
    }
        
    function Connect() {
    /* Creating the WebSocket object automatically initiates communications to the URI to attempt to open the connection asynchronously */
    
        webSocket = new WebSocket(wsUri);
    
        webSocket.onopen = function (e) { 
            console.log("CONNECTED. "); 
        };
        webSocket.onclose = function (e) { 
            console.log("DISCONNECTED."); 
        };
    
        // When a message is received, the onMessage function is called
        webSocket.onmessage = function (e) { 
            console.log("RESPONSE: " + e.data); 
        };
        webSocket.onerror = function (e) { 
            console.log("ERROR: " + e.data); 
        };
    }
    
    function DoSend() {
        var $message = $("#txtMessage");
    
        if (webSocket.readyState != webSocket.OPEN) {
            console.log("NOT OPEN: " + $message.val());
            return;
        }
    
        console.log("SENT: " + $message.val());
        webSocket.send($message.val());
    }