Creating Your Own WebSocket Echo Client

This post introduces a very simple echo client built using WebSockets technology.  The client created here is meant to be used in conjunction with the WebSockets server created in this post. A more comprehensive discussion of the WebSockets API is also available in my post titled “How to Use WebSockets.”

Before running the client, make sure that you’re using a browser that supports WebSockets.  Next, start your WebSockets server.  Finally, create the HTML client page containing the following code.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>WebSocket Echo Client</title>
  <meta charset="UTF-8" />
  <script>
    "use strict";
    // Initialize everything when the window finishes loading
    window.addEventListener("load", function(event) {
      var status = document.getElementById("status");
      var url = document.getElementById("url");
      var open = document.getElementById("open");
      var close = document.getElementById("close");
      var send = document.getElementById("send");
      var text = document.getElementById("text");
      var message = document.getElementById("message");
      var socket;

      status.textContent = "Not Connected";
      url.value = "ws://localhost:8080";
      close.disabled = true;
      send.disabled = true;

      // Create a new connection when the Connect button is clicked
      open.addEventListener("click", function(event) {
        open.disabled = true;
        socket = new WebSocket(url.value, "echo-protocol");

        socket.addEventListener("open", function(event) {
          close.disabled = false;
          send.disabled = false;
          status.textContent = "Connected";
        });

        // Display messages received from the server
        socket.addEventListener("message", function(event) {
          message.textContent = "Server Says: " + event.data;
        });

        // Display any errors that occur
        socket.addEventListener("error", function(event) {
          message.textContent = "Error: " + event;
        });

        socket.addEventListener("close", function(event) {
          open.disabled = false;
          status.textContent = "Not Connected";
        });
      });

      // Close the connection when the Disconnect button is clicked
      close.addEventListener("click", function(event) {
        close.disabled = true;
        send.disabled = true;
        message.textContent = "";
        socket.close();
      });

      // Send text to the server when the Send button is clicked
      send.addEventListener("click", function(event) {
        socket.send(text.value);
        text.value = "";
      });
    });
  </script>
</head>
<body>
  Status: <span id="status"></span><br />
  URL: <input id="url" /><br />
  <input id="open" type="button" value="Connect" />&nbsp;
  <input id="close" type="button" value="Disconnect" /><br />
  <input id="send" type="button" value="Send" />&nbsp;
  <input id="text" /><br />
  <span id="message"></span>
</body>
</html>

Using the Client

As I mentioned, this is a very simple client with the following features.

  • “Status” field ―  This indicates whether or not the client is connected to the server.
  • “URL” field ―  This indicates the connection protocol, as well as the server name and port.  The example server listens on port 8080 and supports the “ws” protocol (“wss” is not supported).
  • “Connect” and “Disconnect” buttons ― These buttons allow the user to open and close WebSockets.  Only one of these buttons is enabled at any given time (i.e. “Disconnect” is disabled if there is no open WebSocket).
  • “Send” button and text box ― When the user presses the “Send” button, the contents of the text box are sent to the server.
  • Messages from the server are displayed as they received.


18 thoughts on “Creating Your Own WebSocket Echo Client

  1. Sorry to ask such an obvious question but:

    I followed your last post and have the “Creating Your Own Node.js WebSocket Echo Server” setup and working.

    How do I connect to it with the client from this tutorial?

    Wil – A complete Node beginner!

    • Wil, just create a blank HTML file on your computer (let’s say client.htm). Paste the example client code into the HTML file. Save the file, then open it in a browser that supports Web Sockets. You should have the server already running on your computer so that the client has something to connect to. Hope this helps, and thanks for reading!

  2. Hello ..
    I created the server explained by you in last post. My server is up and running . Now How can i modify this client such that I am able to make a demo chat application . Please guide. Also , give any other client example please.
    Thank you!

  3. Hello

    Well I m done with Node.js and websockets .. now I need to try another implementation which is jWebSockets. Please help me out with a simple application of websocket with jWebSockets as u did with node.js . One more advantage will be that we would be creating java classes and servlets for the same,so we can upload it on Hudson server for checking the performance of code as well. Please guide asap.
    Thank you!

  4. Hello ..
    I created a stock ticker websocket servlet example and wanted to make it run through jetty using run-jetty-run plugin .
    Everythings works fine and jetty also starts but wen i hit the localhost url , jetty says resource not found . Please have a look,may be your experience might help me out.

    code can be downloaded from here
    http://www.4shared.com/zip/BI4Rx1r_/JettyWebsocketTicket.html?

    and post which i followed was this
    http://ajeeshwrites.blogspot.in/2011/02/peek-at-websockets.html?showComment=1340196182585#c4928101107296080447

    please help… its urgent..M stuck for long
    thank you!

    • Hi Vaibhav,

      I have not used jetty before. I have only developed WebSockets with Node.js. My best suggestion would be to ask the author of the jetty tutorial that you are following. Good luck!

  5. hi cjihrig

    well m stuck for long now… author doesnt seems to be exist anymore. If you or anyone you know could help me out in anyway ,i’ll be grateful.
    after running my application through jetty , and hitting the url localhost:8080/JettyWebSocketTicket/html5.jsp
    it immediately closes the connection with the server.
    Please check it out once.
    thank you!

  6. sir,
    i have already created my websocket and i have also created my client echo,but i got the status as not connected and when i actually try to connect it , does not connect, saying Error:{object event}
    am a begineer at this websocket. please help me sir

      • thanks man…..everything works now…the server is listening to my echo..and what is the next step from here..plz help and give me some ideas..am an eager learner..

        • I’m glad you were able to get the server running. If the client is also working, then the tutorial is done and you can start coming up with ideas for applications. I can’t tell you what to code… just code what interests you.

  7. I have question: how can I make simple chat – I want to output what user enters. Do I need to save data ? Can you help me with this simple task ?