Java Server two-way communication with browser | Simple Websocket example

In this article we will see how Java server (like Tomcat) can have two way communication with browser webpage using websocket API.

You can get history & basic details about websocket on wiki

Example in this article

  • We will create Java server endpoint to listen to websocket connection using javax.websocket.*  API.
  • We will create simple HTML page which will connect to Java server websocket endpoint using simple Javascript.
  • We will deploy this as a war to Tomcat server.
  • We will test exchange of messages both ways between server & browser.



Websocket Java server endpoint

We will create a simple maven web project for this example. We need to add javax.websocket-api  dependency for this example.

Now let’s create a simple endpoint. In this endpoint,

  • On opening of connection, we will start a separate thread which will send messages to browser every 2000 milliseconds.
  • On receiving message from browser, it will print the message in console.





HTML with Javascript Websocket

Now let’s create simple HTML page with Javascript.

  • This page will connect to above Java server websocket endpoint using Javascript Websocket.
  • Every 200 milliseconds, this page will keep sending messages to server.
  • On receiving/sending messages to/from server, it will append the message to HTML to visualize realtime.

Note: ws://  indicates websocket URL & wss://  indicates websocket secure like https. For our example we will use ws:// .

Refer Websocket to get more information about Javascript Websocket object.



Execution

To execute this example, we will use Tomcat server & deploy above example in tomcat. Tomcat server does provide support for websocket.

Here is a video which show demo the code, its deployment to Tomcat using eclipse IDE & browser showcasing exchange of two way messages between server endpoint & browser page.

Output of server

Browser console output

Browser output showing exchange of messages.

GitHub

Complete code can be found on GitHub https://github.com/Ravikharatmal/web-socket-tutorial

Further Reading

You might be interested in this related article.

Create your own video conference web application using Java & JavaScript

References

https://tomcat.apache.org/tomcat-8.0-doc/web-socket-howto.html

https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/WebSocket/WebSocket.html



Leave a Reply

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