How To Use WebSocket In Javascript With Examples

This article will tell you how to use WebSocket in javascript to communicate with the WebSocket server with examples.

1. How To Use WebSocket In JavaScript To Communicate With WebSocket Server.

  1. Create an instance of the javascript WebSocket object, the hostURL parameter is the WebSocket server URL string.
    webSocket = new WebSocket(hostURL);
  2. Add event handler function to the above WebSocket object to handle the onopen, onmessage, onclose events.
    webSocket.onopen = function(){
          ......
    }
    
    webSocket.onmessage = function(msg){
          ......
    }
    
    webSocket.onclose = function(){
          ......
    }
  3. Invoke the WebSocket object’s send(data) function to send the text data to the WebSocket server, this will trigger the WebSocket object’s onmessage event handler function.
    webSocket.send(sendText);
  4. You can get the WebSocket server returned data from the msg.data value passed in the WebSocket object’s onmessage event handler function.
    webSocket.onmessage = function(msg){
          messageDiv.innerHTML += "<p>Server response : " + msg.data + "</p>";
    }
  5. Call the WebSocket object’s close() method to close the WebSocket connection.
    webSocket.close();

2. How To Use WebSocket In JavaScript Example.

  1. There are 1 input text box and 4 buttons in this example.
  2. In the beginning, only the Connect button is enabled, and other buttons are disabled.
  3. When you click the Connect button, it will show the WebSocket communication status information above the input textbox, and then you can click other buttons.
  4. Click the Send Text button to send pure text data to the WebSocket server.
  5. Click the Send JSON Object to send a JSON object to the WebSocket server.
  6. Click the DisConnect can close the WebSocket connection.
  7. There are 2 source files in this example, html5-websocket-example.html, and html5-websocket-example.js.
  8. html5-websocket-example.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Html5 WebSockets Example</title>
    <script type="text/javascript" src="html5-websocket-example.js" charset="utf-8"></script>
    <style>
        .block{
            display:block; 
            margin-top: 10px;
        }
    </style>
    </head>
    <body onload="init()">
    <h3>Html5 WebSockets Example.</h3>
    <div id="message" class="block"></div>
    <p class="block">Please input some text to Send : <input type="text" id="text" onfocus="selectAll()"/></p>
    <button id="connect" onclick="connect()">Connect</button>
    <button id="sendText" onclick="sendText()">Send Text</button>
    <button id="sendJSONObject" onclick="sendJSONOjbect()">Send JSON Object</button>
    <button id="disconnect" onclick="disconnect()">DisConnect</button>
    </body>
    </html>
  9. html5-websocket-example.js.

    var webSocket;
    
    var messageDiv; 
    
    var textInput;
    
    var hostURL;
    
    var websocketReadyStateArray;
    
    var connectBtn;
    
    var sendTextBtn;
    
    var sendJSONObjectBtn;
    
    var disconnectBtn;
    
    function init(){
    
        messageDiv = document.getElementById("message"); 
    
        textInput = document.getElementById("text");
    
        hostURL = "ws://localhost:9999/socket";
    
        websocketReadyStateArray = new Array('Connecting', 'Connected', 'Closing', 'Closed');
    
        connectBtn = document.getElementById('connect');
    
        sendTextBtn = document.getElementById('sendText');
    
        sendJSONObjectBtn = document.getElementById('sendJSONObject');
    
        disconnectBtn = document.getElementById('disconnect');
    
        connectBtn.disabled = false;
    
        sendTextBtn.disabled = true;
    
        sendJSONObjectBtn.disabled = true;
    
        disconnectBtn.disabled = true;
    }
    
    
    function connect(){
    
        try{
    
            webSocket = new WebSocket(hostURL);
    
            messageDiv.innerHTML = "<p>Socket status:" + websocketReadyStateArray[webSocket.readyState] + "</p>";
    
            webSocket.onopen = function(){
    
                messageDiv.innerHTML += "<p>Socket status:" + websocketReadyStateArray[webSocket.readyState] + "</p>";
    
                connectBtn.disabled = true;
    
                sendTextBtn.disabled = false;
    
                sendJSONObjectBtn.disabled = false;
    
                disconnectBtn.disabled = false;
            }
    
            webSocket.onmessage = function(msg){
    
                messageDiv.innerHTML += "<p>Server response : " + msg.data + "</p>";
            }
    
            webSocket.onclose = function(){
    
                messageDiv.innerHTML += "<p>Socket status:" + websocketReadyStateArray[webSocket.readyState] + "</p>";
    
                connectBtn.disabled = false;
    
                sendTextBtn.disabled = true;
    
                sendJSONObjectBtn.disabled = true;
    
                disconnectBtn.disabled = true;
            }
    
        }catch(exception){
    
            messageDiv.innerHTML += 'Exception happen, ' + exception;
        }
    }
    
    
    
    function sendText(){
    
        var sendText = textInput.value.trim();
    
        if(sendText==''){
            
            messageDiv.innerHTML = '<p>Please input some text to send.</p>';
    
            return;
    
        }else{
    
            try{
                
                webSocket.send(sendText);
    
                messageDiv.innerHTML = '<p>Send text : ' + sendText + '</p>'
    
            }catch(exception){
    
                messageDiv.innerHTML = '<p>Send error : ' + exception + '</p>'
    
            }
        }
    
    
    }
    
    function sendJSONOjbect(){
    
        var sendText = textInput.value.trim();
    
        if(sendText==''){
            
            messageDiv.innerHTML = '<p>Please input some text to send.</p>';
    
            return;
    
        }else{
    
            try{
    
                currDate = new Date();
    
                currHour = currDate.getHours();
    
                currMinutes = currDate.getMinutes();
    
                currSeconds = currDate.getSeconds();
                
                currentTime = currHour + ':' + currMinutes + ':' + currSeconds;  
    
                jsonObj = {time:currentTime, text:sendText}
    
                tmpSendText = JSON.stringify(jsonObj)
    
                webSocket.send(tmpSendText);
    
                messageDiv.innerHTML = '<p>Send JSON object : ' + tmpSendText + '</p>'
    
            }catch(exception){
    
                messageDiv.innerHTML = '<p>Send error : ' + exception + '</p>'
    
            }
        }
    
    }
    
    // When you focus on the input text box, it will call this function to select all the text in the input text box.
    function selectAll(){
    
        textInput.select();
    
    }
    
    
    function disconnect(){
    
        webSocket.close();
    
    }
  10. If you want to create a WebSocket server, you can read the article How To Use Python To Create WebSocket Server & Client Example.
  11. Below is this example demo video.

1 thought on “How To Use WebSocket In Javascript With Examples”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.