Thursday, March 15, 2018

Javascript WebSocket Client Example

In javascript WebSocket API below are the methods that you may need to implement when communicating with a server.
  websocket.onopen - This method gets executed when a connection between the client and the server is created.
  websocket.onclose - This method gets executed when a connection is closed.
  websocket.onmessage This method gets executed when a message is received from server.
  websocket.onerror - This will be called if an unhandled error is thrown in above methods.

Below HTML page contains a sample code.

<!DOCTYPE HTML>
<html>
   <head>
      <script type="text/javascript">
         var ws;
         function loadWebsocket() {
            if (window.WebSocket) {
               //The browser supports WebSockets");
               // Open a web socket
               ws = new WebSocket("ws://localhost:8080/WebsocketServer1/chat");
               ws.onopen = function() {
                  console.log("Connection is opened...");
               };

               ws.onmessage = function (evt) { 
                  var message = evt.data;
                  console.log("Message is received...:" + message);
               };

               ws.onclose = function() { 
                  console.log("Connection is closed..."); 
               };

ws.onerror = function() {
console.log("Error occured...");
};
               
               window.onbeforeunload = function(event) {
                  socket.close();
               };
            } else {
               // The browser doesn't support WebSocket
               console.log("Your browser doesn't support WebSockets!");
            }
         }
 
         function sendMessage() {
          ws.send("Hello server!");
        }
        
         loadWebsocket();
      </script>

   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:sendMessage()">Send message</a>
      </div>
      
   </body>
</html>