HTML and CSS Reference
In-Depth Information
server and embedding Jetty within the web application. The main reasoning behind this
approach is to take advantage of a lightweight Java EE 6.0 [Full Profile] application
server. There are a few other Java options out there, such as GlassFish or running Jetty
standalone, but this solution offers contexts and dependency injection (CDI), distribut‐
ed transactions, scalable JMS messaging, and data grid support out of the box. Such
support is extremely valuable in cutting-edge enterprise initiatives and private cloud
Because this approach embeds one server (Jetty) with another server (JBoss), we can
use it with any app server, even one that may not support WebSockets, and enable
existing, older applications to take advantage of real-time connections.
The full deployable source code for this example is on the embedded-jetty branch ”. A
few things are worth noting here:
Because the WebSocket server is running on a different port (8081) than the JBoss
AS7 server (8080), we must account for not having authentication cookies, and so
on. A reverse proxy can handle this problem, however, as you'll see in the last section
of this chapter.
As if existing proxy servers weren't already a huge problem for running WebSockets
and HTTP over the same port, in this example, we are now running them separately.
Because we're observing and listening for CDI events, we must perform some same
thread operations and connection sharing.
The code below first sets up the WebSocket server using Jetty's WebSocketHandler and
embeds it inside a ServletContextListener . Although the app shares a synchronized
set of WebSocket connections across threads, we ensure that only a single thread can
execute a method or block at one time by using the synchronized keyword. To relay
the CDI event to the browser, we must store all the WebSocket connections in a Concur
rentHashSet and write new connections to it as they come online. At any time, the
ConcurrentHashSet will be read on a different thread so we know where to relay the
CDI events. The ChatWebSocketHandler contains a global set of WebSocket connections
and adds each new connection within the Jetty server.
public class ChatWebSocketHandler extends WebSocketHandler {
private static Set < ChatWebSocket > websockets =
new ConcurrentHashSet < ChatWebSocket >();
public WebSocket doWebSocketConnect ( HttpServletRequest request ,
String protocol ) {
return new ChatWebSocket ();
Search WWH ::

Custom Search