[ DWR Website | Web Application Index ]

Javascript Chat

This is a very simple chat demo that uses reverse ajax to collect messages and Javascript to manipulate the pages with the results.

Your Message:


Sending a Message

The code begins by turning active reverse ajax on (see the clock demo for more details). We then wait for the user to press the 'Send' button, when they do, the following happens:

var text = dwr.util.getValue("text");
dwr.util.setValue("text", "");
JavascriptChat.addMessage(text);

We get the value out of the message field, clear it, and send the message to the server. The addMessage method on the server looks like this:

if (text != null && text.trim().length() > 0) {
    messages.addFirst(new Message(text));
    while (messages.size() > 10) {
        messages.removeLast();
    }
}

Browser.withCurrentPage(new Runnable() {
    public void run() {
        ScriptSessions.addFunctionCall("receiveMessages", messages);
    }
});

We check that the message isn't too long, and then add it to our list of messages, which we push to all browsers on the same page as us by calling the receiveMessages() function in the browser, which looks like this:

var chatlog = "";
for (var data in messages) {
  chatlog = "
" + dwr.util.escapeHtml(messages[data].text) + "
" + chatlog; } dwr.util.setValue("chatlog", chatlog, { escapeHtml:false });

We simply create a set of divs that contain the chat messages, and add them to the chatlog element.

HTML source:

<p>
  Your Message:
  <input id="text" onkeypress="dwr.util.onReturn(event, sendMessage)"/>
  <input type="button" value="Send" onclick="sendMessage()"/>
</p>
<hr/>
<div id="chatlog"></div>

Javascript source:

function init() {
  dwr.engine.setActiveReverseAjax(true);
}

function sendMessage() {
  var text = dwr.util.getValue("text");
  dwr.util.setValue("text", "");
  JavascriptChat.addMessage(text);
}

function receiveMessages(messages) {
  var chatlog = "";
  for (var data in messages) {
    chatlog = "
" + dwr.util.escapeHtml(messages[data].text) + "
" + chatlog; } dwr.util.setValue("chatlog", chatlog, { escapeHtml:false }); }

Java source:

public class JavascriptChat {
    /**
     * @param text The new message text to add
     */
    public void addMessage(String text) {
        if (text != null && text.trim().length() > 0) {
            messages.addFirst(new Message(text));
            while (messages.size() > 10) {
                messages.removeLast();
            }
        }

        Browser.withCurrentPage(new Runnable() {
            public void run() {
                ScriptSessions.addFunctionCall("receiveMessages", messages);
            }
        });
    }

    /**
     * The current set of messages
     */
    private final LinkedList<Message> messages = new LinkedList<Message>();
}