Blog Image

Java Web Socket  

Java WebSocket api provided in javax.websocket package. Why WebSocket is required and how it can be used in application is given as part of this blog. The annotations provided by the WebSockets and their use is given as part of the example.

WebSocket is an application protocol that provides full-duplex communications between two endpoints over the TCP protocol.

Previously in HTTP request-response model, client has to send the request to the server endpoint and server has to provide response for that client request. The communication between client and server was always initiated by client. The server cannot send any data without client request by its own. As the data was not changing frequently this request-response model worked. But as the data started changing frequently and the users also expect more responsive server, the WebSocket protocol addresses these requirements by providing a full-duplex communication channel between client and server by using other client technologies like JavaScript and HTML5.

The server publishes a WebSocket endpoint and the client uses the endpoint's URI to connect to the server. When the connection between the client and server is open the client and the server can send messages to each other. Clients can connect only to one server but the servers can accept connections from multiple clients.

When the client send the request to the WebSocket endpoint by using URI the handshake is initiates. Web servers interpret it as an HTTP connection upgrade request. In the header of handshake one property is there called 'Sec-WebSocket-Key'. On the value of this property server will perform one operation which produces a result. The client will also perform the same operation on that property value and checks both the result are same or not. If both the results are same then the handshake is successful and client and server can communicates over the network.

The Java API for WebSocket consists of the following packages.

The javax.websocket.server package contains annotations, classes, and interfaces to create and configure server endpoints.
The javax.websocket package contains annotations, classes, interfaces, and exceptions that are common to client and server endpoints.

WebSocket endpoints are instantiated multiple times. The container creates an instance of an endpoint per connection to its deployment URI. Each instance is associated with one and only one connection. This facilitates keeping user state for each connection.

 WebSocket endpoint life cycle events are handled with the help of the following annotations:

  •     @OnOpen: This annotation enables the java method to handle a connection open event
  •     @OnMessage: This annotation enables the java method to handle an event on message received
  •     @OnError: This annotation enables the java method to handle a connection error event
  •     @OnClose: This annotation enables the java method to handle an event on connection close

The following program shows how the above annotations can be used. In this program, one java class has been created as a server endpoint using the above annotations. The client has been created as part of client.jsp. The when we run the application, the connection will be created with the server. Then client can send request to the server. The server will receives the request and communicates with client based on the request.
The java class acting as server:

public class WebSocketServer {
    public void onOpen() {
        System.out.println("Open Connection ...");

    public void onClose() {
        System.out.println("Close Connection ...");

    public String onMessage(String message) {
        System.out.println("Message from the client: " + message);
        String msg = "Message Recieved from the server : " + message;
        return msg;

    public void onError(Throwable e) {


client.jsp as client:

<!DOCTYPE html>
<meta charset="UTF-8">
        <input id="message" type="text"> <input
            onclick="wsSendMessage();" value="Send" type="button"> <input
            onclick="wsCloseConnection();" value="Disconnect" type="button">
    <textarea id="text" rows="10" cols="60"></textarea>
    <script type="text/javascript">
        var webSocket = new WebSocket(
        var text = document.getElementById("text");
        text.value = "";
        var message = document.getElementById("message");
        webSocket.onopen = function(message) {
        webSocket.onmessage = function(message) {
        webSocket.onclose = function(message) {
        webSocket.onerror = function(message) {
        function wsOpen(message) {
            text.value += "Connected to the Server... \n";
        function wsSendMessage() {
            text.value += "Message sent to the Server : " + message.value
                    + "\n";
            message.value = "";
        function wsCloseConnection() {
        function wsGetMessage(message) {
            text.value += + "\n";
        function wsClose(message) {
            text.value += "Disconnect from the Server... \n";

        function wserror(message) {
            text.value += "Error occured in operation... \n";

The output for the above program is as follows:

You can download the above maven example from attachment given below.

About author

User Image

I am a software developer. I am working working on jdk , jee technologies. I am working on Spring Framework as well. I am passionate about learning java technologies like Web Services and Restful Services.



Be the first person to write a comment for this Blog
Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.