Saturday, 9 August 2014

Java API for websockets

From the previous two posts, I hope you got some basic understanding of websocket API. It is time to explore the Java API support for websocket in detail.

In a websocket Application server publish an end point and client connect to the server using endpoint URI. Once the connection is established, client and server acts as peers and can able to transfer 'n' number of messages in between. Websockets supports both text and binary messages.

In HTTP we had unencrypted (http) and encrypted(https) connection. Same like web socket also provides both unencrypted and encrypted connections.

Unencrypted Connection
The ws scheme represents an unencrypted WebSocket connection. The default port number is 80 for unencrypted connections.
Example
  ws://localhost:8080/websockets/endpoint

Encrypted Connection
The wss scheme represents an encrypted WebSocket connection. The default port number is 443 for encrypted connections.
Example
   ws://localhost:8080/websockets/endpoint

Almost all web browsers implement websocket protocol and and provide a JavaScript API to connect to endpoints.

You can get the list of browsers and their versions that support websockets from below link.

"http://caniuse.com/websockets".

The Java API for web sockets consist of below packages.
     javax.websocket.server
     javax.websocket

Package Description
javax.websocket.server This package contains all the WebSocket APIs used only by server side applications.
javax.websocket This package contains all the WebSocket APIs common to both the client and server side.

Java API provides two ways to create server end points.
  1. programmatic server endpoint
  2. annotated server endpoint
You can create programmatic endpoint by extending 'javax.websocket.Endpoint' class.

You can create annotated endpoint by decorating a Java class and some of its methods with the annotations provided by the packages. After creating endpoint you must deploy it to an specific URI in the application so that remote clients can connect to it.

As opposed to servlets (Where only one instance created to handle all the requests), WebSocket endpoints are instantiated multiple times. Container creates an instance of an endpoint per connection to its deployment URI.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment