Monday Feb 25, 2013

Chat Sever using WebSocket in GlassFish 4 (TOTD #207)


A canonical example of using WebSocket is a chat server. This Tip Of The Day (TOTD) will share the code for building exactly that!

The complete code in this TOTD is available here.

Here is the code for the Chat Server built as a WebSocket endpoint:

@WebSocketEndpoint("/websocket")
public class ChatEndpoint {
private static final Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

@WebSocketOpen
public void onOpen(Session peer) {
peers.add(peer);
}

@WebSocketClose
public void onClose(Session peer) {
peers.remove(peer);
}

@WebSocketMessage
public void message(String message, Session client) throws IOException, EncodeException {
for (Session peer : peers) {
peer.getRemote().sendObject(message);
}
}
}

In this code:
  • Lifecycle callbacks manage the coordinates of the connecting clients
  • message method receives all the messages sent by the client and then transmits to all the connected clients.
Simple, isn't it ?

You can use a trivial JavaScript to exchange messages between two browsers. A chat session between two Chrome and Firefox is shown below:



Download the source code and run it in GlassFish 4 b77.

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« February 2013 »
SunMonTueWedThuFriSat
     
2
3
4
5
6
9
10
12
14
15
16
17
20
21
22
23
24
  
       
Today