JavaFX chat client with Comet server

I have written a few entries about a JavaFX chat client and about a Comet Chat engine. Now, I have put together the simplest examples I could come up with.

Both the ChatServer (using Comet) and the ChatClient (in JavaFX) can be downloaded here.
Some remarks:

Comet based ChatServer

The ChatServer directory contains a Netbeans project that uses Comet in GlassFish v2. If you want to run this example in GlassFish v3, you have to change the package name com.sun.enterprise.web.connector.grizzly.comet; into com.sun.grizzly.comet.CometContext . The ChatServer contains 3 classes:

ChatEntry

This is a POJO, containing the information about chat entries (only a username and a text are used).

ChatServlet

This is the entry point for clients. Comet initialization is done in the init(ServletConfig config) method. Incoming requests have a parameter method. This parameter can have two values: listen and chat.

listen

A new CometHandler is created, and the PrintWriter of the HttpServletResponse is attached to the CometContext When new chat entries are received, the CometHandler will send the content to the attached writer.

chat

An incoming chat entry is received. The CometContext is notified about this event, and it will send the chat text to all registered listeners.

ChatHandler

This is our implementation of the CometHandler. When a client starts listening, a new instance of the ChatHandler is created, and the PrintWriter connected to the ServletResponse is stored. When new chat entries are received, the onEvent method will be called, and the chat text will be written to the PrintWriter instance.

 

JavaFX ChatClient

The ChatClient is slightly more complicated. See one of my previous blog entries for a detailed description of a JavaFX chat client. The example described in today's entry is simplified a bit. We don't use a separate class for writing new chat entries, but we use the HttpRequest for calling a url containing the chat entry information. We can't use the same approach for reading incoming chat entries, since the onInput function of the HttpRequest is only called when all input has been read. The existing javafx.data packages are very suitable for reading message-based content (i.e. RSS feeds), but not for streaming. Hence, we created a mechanism where a callback interface (ChatInput is called each time the InputStream receives a new chat entry). This is done by means of the FXReader JavaFX class and the AsyncReader java class. Again, for implementation details have a look at my previous blog entry.

 

At LodgON, we are working on a product that contains chat functionality. It is more complex than the example we've shown here, i.e. the chat can be moderated, users can have different roles, documents can be shown,... . The basic principles of the chat interactions are the same, though.

written on 14 Sep 2009 12:23.

no comments

Create comment