Close

Java EE - WebSocket Hello World Example

[Last Updated: Feb 23, 2017]

This is a quick demonstration of Java WebSocket API with maven and embedded Jetty.

The WebSocket specification allows bi-directional communication session between client and server. This is an HTML5 based solution for HTTP statelessness.

Maven dependencies

Java EE 7 dependency

<dependencies>
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
  </dependency>
</dependencies>

Jetty Plugin

<plugin>
  <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.4.1.v20170120</version>
    <configuration>
        <webApp>
            <contextPath>/example</contextPath>
        </webApp>
  </configuration>
</plugin>

Java WebSocket server endpoint

This example uses Java WebSocket annotations to define a server endpoint.

@ServerEndpoint("/hello")
public class HelloWorldEndpoint {

  public HelloWorldEndpoint() {
      System.out.println("class loaded " + this.getClass());
  }

  @OnOpen
  public void onOpen(Session session) {
      System.out.printf("Session opened, id: %s%n", session.getId());
      try {
          session.getBasicRemote().sendText("Hi there, we are successfully connected.");
      } catch (IOException ex) {
          ex.printStackTrace();
      }
  }

  @OnMessage
  public void onMessage(String message, Session session) {
      System.out.printf("Message received. Session id: %s Message: %s%n",
              session.getId(), message);
      try {
          session.getBasicRemote().sendText(String.format("We received your message: %s%n", message));
      } catch (IOException ex) {
          ex.printStackTrace();
      }
  }

  @OnError
  public void onError(Throwable e) {
      e.printStackTrace();
  }

  @OnClose
  public void onClose(Session session) {
      System.out.printf("Session closed with id: %s%n", session.getId());
  }
}

We don't need any extra configuration for the above endpoint to be deployed. The annotations will be scanned and discovered automatically.

WebSocket JavaScript client

Following is the JavaScript based WebSocket client.

web-socket-client.html

<html>

<body style="margin: 35px">
<form>
    <input id="messageField" type="text">
    <input onclick="sendMsg();" value="send" type="button">
</form>

<div id="msg-box" style="width:500px; height: 400px; background: #eee; overflow:auto;"></div>


<script>
    var webSocket = new WebSocket("ws://localhost:8080/example/hello");
    var msgField = document.getElementById("messageField");
    var divMsg = document.getElementById("msg-box");

    function sendMsg() {
        var msgToSend = msgField.value;
        webSocket.send(msgToSend);
        divMsg.innerHTML += "<div style='color:red'>Client> " + msgToSend +
                            "</div>"
        msgField.value = "";
    }

    webSocket.onmessage = function(message) {
                divMsg.innerHTML += "Server> : " + message.data;

            }

    webSocket.onopen = function() {
        console.log("connection opened");
    };

    webSocket.onclose = function() {
        console.log("connection closed");
    };

    webSocket.onerror = function wserror(message) {
        console.log("error: " + message);
    }


</script>
</body>
</html>

Running Jetty

mvn jetty:run

Output

Open the html page from the file system (outside of the Servlet container). The JavaScript client will connect to the server immediately. Now enter some messages:

Server console output:

 .............
[INFO] Started Jetty Server
class loaded class com.logicbig.example.HelloWorldEndpoint
Session opened, id: 0:0:0:0:0:0:0:1:8080->0:0:0:0:0:0:0:1:56177
Message received. Session id: 0:0:0:0:0:0:0:1:8080->0:0:0:0:0:0:0:1:56177 Message: Hi from JavaScript
Message received. Session id: 0:0:0:0:0:0:0:1:8080->0:0:0:0:0:0:0:1:56177 Message: Message 2 from JS

Example Project

Dependencies and Technologies Used:

  • javaee-api 7.0: Java(TM) EE 7 Specification APIs.
  • JDK 1.8
  • Maven 3.3.9

Java Web Socket Example Select All Download
  • web-sockets-hello-world
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • HelloWorldEndpoint.java

    See Also