Java Reference
In-Depth Information
Asynchronous versus synchronous messages
You might be wondering which message to use: synchronous or asynchronous. For most
applications, it's better to go with asynchronous messages. Synchronous messages will res-
ult in your code slowing down and waiting on a slow client. If you're iterating over a list
of Session objects and sending out a broadcast message, one slow client will slow mes-
sages to all clients. Furthermore, if you're in the middle of a transaction and send out a
synchronous message, you'll lock that resource until the message is sent. You don't want
to couple database table locking to slow WebSocket connections. This is a recipe to create
a nonscalable application.
Synchronous messages aren't a solution to concurrency issues. Design both your server and
the client for asynchronous communication. Assume that connections will drop and the end
user might be on a 2G cell network.
Closing WebSocket connection
Once you're finished with a WebSocket connection, it's important to close it. WebSocket
connections will live for a long time if you forget about them. They are expensive even if
little data is being transmitted over them. The Session object provides two methods for
closing a WebSocket connection:
close() throws IOException;
close(CloseReason closeReason) throws IOException;
The first close method, lacking a reason, closes the connection with a normal status code
and no reason. The second close method enables you to provide a reason for closing the
connection. In ActionBazaar if the web application is undeployed or the server is shut down
(normally), all of the open WebSocket connections are closed and the following message is
provided to the client so it may inform the user:
session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY,
"Server is going down for maintenance."));
Acquiring basic WebSocket information
The WebSocket Session interface also provides a wealth of information about the cur-
rent client and type of connection. Some of the more useful methods are as follows:
Search WWH ::




Custom Search