Introduction
Since last decade web has changed a lot. Now web applications are more responsive continuously talking to servers without reloading the whole page again. Technologies like Ajax is doing very good in this field. But there is always a question "What next?". WebSocket might be answer to that.
WebSocket is technology which provide full duplex communication channels over a single TCP connection. So in simple words, the client will open a TCP connection and start sending and receiving the data. All latest browsers support WebSocket. Now I want to jump to the part where Websocket met Java EE, if you want to read more about WebSocket here is Wiki Link.
WebSocket is technology which provide full duplex communication channels over a single TCP connection. So in simple words, the client will open a TCP connection and start sending and receiving the data. All latest browsers support WebSocket. Now I want to jump to the part where Websocket met Java EE, if you want to read more about WebSocket here is Wiki Link.
WebSocket & Java EE
Java EE 7 is going to be first version which will officially add WebSocket as an option for developers. So here is the list of Ingredients required to write a simple WebSocket application:- Script file written in JavaScript
- A POJO with WebSocket Annotations
Example :
There are two annotations which will convert POJO to a webSocket.
- WebSocketEndpoint - URL pattern along with some encoder and decoder information is defined using this annotation.
- WebSocketMessage - method with this annotation is called to process the message and produce any response (if required)
On client side, WebSocket class has been introduced to JavaScript. To start communication with WebSocket, we need to create a new object of WebSocket and need to register few callback methods which will be called on different state of connection and messaging.
Lets check how it looks like:
The code will produce following output:
So as soon as the page is loaded the browser will try to open WebSocket if WebSocket is opened successfully onOpen method will be called. Then user need to enter some Data in text box and click greet button. Then send method will be called to send the data to WebSocket. Then WebSocket will process the data (in our example sayHello method will process the message) and send back the message. As soon as the browser receives the message onMessage method will be invoked and desired operation will be performed.
In this screenshot I tried to capture the network communication using Google Chrome developers tools. You can clearly see there is single connection used again for all transmission.