[ DWR Website | Web Application Index ]

# Java Chat

This is a very simple chat demo that uses reverse ajax to collect messages and server-side browser manipulation to update the pages with the results.

- Demo
- How it works
- Source

Your Message:

## Sending a Message

This code is similar to the JavaScript Chat demo except that we've moved more processing to the server in this case. With this version we simply send whatever is typed to the server on a keypress.

    function sendMessage() {
      JavaChat.addMessage(dwr.util.getValue("text"));
    }

And the server processes the input as it did in the JavaScript Chat example, except that rather than call a JavaScript function to update the UI it does it itself:

First it clears the message input field. Since the default target browser is the browser that caused the event to happen, we can just call setValue as follows:

    Util.setValue("text", "");

We then need to change the target browsers to include everyone on the same page before we alter the list of current messages:

    // For all the browsers on the current page:
    Browser.withCurrentPage(new Runnable() {
        public void run() {
            // Clear the list and add in the new set of messages
            Util.removeAllOptions("chatlog");
            Util.addOptions("chatlog", messages, "text");
        }
    });

## 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:

    dwr.engine.setActiveReverseAjax(true);

    function sendMessage() {
      JavaChat.addMessage(dwr.util.getValue("text"));
    }

## Java source:

    public class JavaChat {
        /**
         * @param text The new message text to add
         */
        public void addMessage(String text) {
            // Make sure we have a list of the list 10 messages
            if (text != null && text.trim().length() > 0) {
                messages.addFirst(new Message(text));
                while (messages.size() > 10) {
                    messages.removeLast();
                }
            }

            // Clear the input box in the browser that kicked off this page only
            Util.setValue("text", "");

            // For all the browsers on the current page:
            Browser.withCurrentPage(new Runnable() {
                public void run() {
                    // Clear the list and add in the new set of messages
                    Util.removeAllOptions("chatlog");
                    Util.addOptions("chatlog", messages, "text");
                }
            });
        }

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