Java WebSocket API

The WebSocket API expresses a view of the HTML5 standard for WebSocket, which defines the model inside a web browser and the protocol for communication. In terms of the Java API, a WebSocket endpoint is a Java object that represents a terminated socket connection between two peers. If two different Java applications have a Web Socket connection, then each one will have an instance of a Java WebSocket.

There are two ways to create a Java WebSocket. The easiest way is to develop endpoints using the Java annotations. The less travelled road is to develop endpoints against the WebSocket API programmatically. The developer writes classes and implements the classes required by the WebSocket API. The second way means the developer writes behavior for a WebSocket to produce and consume messages, publish itself as a configured endpoint, and write code to register itself for client connections and/or connect to remote endpoints.

Native formats communication

The HTML5 standard for WebSocket defines three native formats for communication: text, binary, and pong.

The native format Text is the java.lang.String in Java and for JavaScript programming language corresponds to the type String. So we have a one-to-one association.

Binary format is java.nio.ByteBuffer in Java and the type ArrayBuffer in JavaScript. (Some web browsers may also permit the DOM type Blob in JavaScript; since the standard is not completely ratified, you would be very wise to check your integration!)

The Pong format is also java.nio.ByteBuffer in Java and the type ArrayBuffer in JavaScript. The Ping and Pong format is a special format for checking the connectivity between two WebSockets. In the networking parlance, these types of messages are often called heartbeats. In the current WebSocket standard, please note there is no defined API to send either a Ping or Pong message using JavaScript.

Let's continue with the annotated WebSocket endpoints.

Annotated WebSockets on the server side

Developers have access to the lifecycle of the WebSocket through annotations, which unsurprisingly are very similar to the JavaScript implementation. The annotations are @javax.websocket.OnMessage, which you have already seen @javax.websocket.OnOpen, @javax.websocket.OnClose, and @javax.websocket.OnError. These annotations, apart from @OnMessage, do not accept any attributes. All of the annotations are only applied to instance methods in a Java class.

Lifecycle WebSocket endpoint annotations

Here is a table of these annotations:

Lifecycle Annotation

Description

@OnOpen

This annotation decorates a Java method that wishes to be called when a new WebSocket session is open.

@OnMessage

This annotation decorates a Java method to receive incoming WebSocket messages. Each WebSocket endpoint may only have one message handling method for each of the native WebSocket message formats: text, binary, and pong.

@OnClose

This annotation decorates a Java method that wishes to be called when an existing WebSocket session is closed.

@OnError

This annotation decorates a Java method that wishes to be called when an existing WebSocket session has an error. The application method can thus handle the error and perform further tasks.

This method-level annotation can be used to make a Java method receive incoming WebSocket messages. Each WebSocket endpoint may only have one message handling method for each of the native WebSocket message formats: text, binary, and pong.

WebSocket sessions

The Java WebSocket API defines a session object that represents a conversation between two peers. The javax.websocket.Session is an interface, which defines a number of methods that a developer may invoke to get extra information about the connection, session data, the lifecycle, and also perform the close action on the connection. Moreover, the Session object is the way to associate the conversation with the peer into a semantic context in terms of a business application.

Each WebSocket session has a unique session ID, which is associated with one and only one session instance. An implementation may choose to implement a WebSocket connection pool and therefore an instance may be appropriately reused. In such cases, the specification stipulates that a reused session instance must have a new unique session ID.

The session instance in a distributed Java EE container can also be passivated on managed server node instance and therefore migrated to another node. Implementations of the Java WebSocket API are permitted to migrate the WebSocket session instances from one node to another for the purposes of load balancing and failover. The only rule is that the provider must preserve the WebSocket session of any connected peers seamlessly and transparently. This is particularly interesting from the point of view of a cloud-computing platform. This, probably, will be a common question for application architects. How do WebSocket connections, nodes, and servers scale? The simplest answer, perhaps, is to choose a provider that reliably has the non-functional requirements that your business needs.

Methods annotated with lifecycle events@OnOpen, @OnClose, @OnMessage, and @OnError annotation are permitted to accept a javax.websocket.Session object as an argument. The implementation will inject the session instance into the method call.

Methods annotated with@OnMessage annotation additionally can also declare a @javax.websocket.PathParam argument in order to accept WebSocket connection arguments.

Here is a table for the methods of javax.websocket.Session:

Method

Return Type

Description

getContainer()

WebSocketContainer

Gets the container of which this session is a part.

addMessageHandler( MessageHandler handler)

void

Registers a handler to receive incoming messages in the session conversation (text, binary or pong).

getMessageHandlers()

Set<MessageHandler>

Retrieves an immutable copy of the set of MessageHandler associated with the session.

removeMessageHandler( MessageHandler handler )

void

Removes the supplied MessageHandler from the set of handlers associated with this session. If the message handler is in use then invoking this call may block the caller.

getProtocolVersion()

String

Gets the version of the WebSocket protocol currently being used.

getNegotiated-Subprotocol()

String

Gets the sub protocol agreed after the WebSocket handshake for this conversation.

getNegotiated-Extensions()

List<Extension>

Retrieves a list of extensions that have been agreed for use in the session conversation.

isSecure()

boolean

Returns a Boolean flag about the underlying socket connection. If a secure transport is being used (https) then this method returns true.

isOpen()

Boolean

Returns a Boolean flag, if the socket connection is open or closed.

getMaxIdleTime()

Long

Specifies the number of milliseconds allowed before the container closes a WebSocket channel.

setMaxIdleTime( long millisecond)

void

Sets the number of milliseconds before the conversation is ended, because of inactivity, which means no data is sent or received over a period of time.

setMaxBinaryMessage-BufferSize( int length)

void

Sets the maximum length of incoming binary messages.

getMaxBinaryMessage-BufferSize()

int

Gets the maximum length of incoming binary messages.

setMaxTextMessage-BufferSize( int length)

void

Sets the maximum length of incoming text messages.

getMaxTextMessage-BufferSize()

int

Gets the maximum length of incoming text messages.

getAsyncRemote()

RemoteEndpoint.Async

Returns a reference to a RemoteEndpoint object, which represents the peer of the conversation that is able to send messages asynchronously to the peer.

getBasicRemote()

RemoteEndpoint.Basic

Returns a reference to a RemoteEndpoint object, which represents the peer of the conversation that is able to send messages synchronously to the peer.

getId()

String

Gets the unique identifier for this session instance.

close()

void

Closes the current conversation with a normal status code and no reason text.

close(CloseReason reason)

void

Closes the current conversation with a specific reason for ending the session.

getRequestURI()

URI

Retrieves the URI under which this session was opened including the full query string.

getRequestParameter-Map()

Map<String, <List<String>>

Retrieves a map collection of the request parameters associated with the request and also the underlying session.

getQueryString()

String

Returns the query string associated with the request for this session at opening time.

getPathParameters()

Map<String, String>

Retrieves a map collection of the path parameters and values associated with the request for this session at opening time.

getUserProperties()

Map<String, Object>

Retrieves a map collection of user-defined properties. This map is valid when the connection is open and therefore any information is at risk as soon as the connection session is closed.

getUserPrincipal()

Principal

Gets the authenticated user for this WebSocket session object or null if there is no authenticated user.

getOpenSessions()

Set<Session>

Returns a copy of the set collection of all the open WebSocket sessions that represent connections to the same endpoint, to which this session represents a connection.

Although there are lots of methods in javax.websocket.Session, the most important methods are: getId(); getRemoteBasic() and getRemoteAsync(); isOpen(), close(), and getRequestParameterMap().

Now let us see a more capable server-side WebSocket application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.73.175