Java Reference
In-Depth Information
14.5. Using WebSockets effectively
WebSockets are a powerful addition to the Java EE stack and make it possible to develop
applications that receive data from the server asynchronously. Clients no longer need to
poll the server to check for updates—the server can now push messages back to the client.
Unlike RESTful and SOAP-based web services, WebSocket endpoints are stateful. There
are two elements of state here: there are objects that are kept in memory on the server (en-
dpoint), and a socket connection is kept open to the client. If a given page opens two We-
bSocket connections to the server, as in the case of the ActionBazaar example with the chat
and bulletin services, there are now two sets of objects and two expensive socket connec-
tions. WebSockets reduce the scalability of an application, but also makes it possible to
provide push notifications from the server to the client in a standards-based approach that's
superior to polling with AJAX or using nonstandard Comet.
To use WebSockets effectively, there are several important practices:
• Use WebSockets only when AJAX isn't a suitable solution.
• Store state in the user properties on the session, accessed via Ses-
sion.getUserProperties() .
• Use EJBs for accessing transaction-based resources like databases.
• Use subprotocols to support versioning.
• Exchange data using JSON.
• Limit clients to one WebSocket connection.
• Set message size limits on WebSocket messages.
• Secure WebSocket endpoints using realm security.
• Use HTML5 WebSocket Security (WSS) whenever possible.
WebSockets are an exciting new HTML5 technology, but they aren't appropriate for every
problem. WebSockets should be used only where push notifications from the server to the
client are necessary. In the case of ActionBazaar, the chat service is one such case, because
you don't want the client polling the server for new messages. But WebSockets wouldn't
be an appropriate solution for performing web form validation, such as checking to make
sure a username doesn't already exist when creating a new account. AJAX is still the ap-
propriate solution for such situations. Also, in the case of ActionBazaar, it wouldn't be a
good idea to use WebSockets from the main page to the application. You don't want every
page view to result in a socket connection to the server.
Search WWH ::




Custom Search