Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 290353
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T05:59:24+00:00 2026-05-12T05:59:24+00:00

I have implemented the two classes shown at http://tomcat.apache.org/tomcat-6.0-doc/aio.html which gives a messenger application

  • 0

I have implemented the two classes shown at http://tomcat.apache.org/tomcat-6.0-doc/aio.html which gives a messenger application using Tomcat’s comet implementation.

How do I connect this to a web interface and get something to display.

I am thinking these are the basic steps (I don’t know the details).

  1. I should create some traditional event – a button click or AJAX event – that calls the ChatServlet and passes in a CometEvent (somehow) – perhaps BEGIN
  2. From then I have my code call the event method every time I want to send something to the client using the READ event as the input parameter.

I have copied the two classes below:


package controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.CometEvent;
import org.apache.catalina.CometProcessor;

public class ChatServlet extends HttpServlet implements CometProcessor {

protected ArrayList<HttpServletResponse> connections = new     ArrayList<HttpServletResponse>();
protected MessageSender messageSender = null;

public void init() throws ServletException {
    messageSender = new MessageSender();
    Thread messageSenderThread = new Thread(messageSender, "MessageSender["
            + getServletContext().getContextPath() + "]");
    messageSenderThread.setDaemon(true);
    messageSenderThread.start();
}

public void destroy() {
    connections.clear();
    messageSender.stop();
    messageSender = null;
}

    /**
     * Process the given Comet event.
     * 
     * @param event
     *            The Comet event that will be processed
     * @throws IOException
     * @throws ServletException
     */
public void event(CometEvent event) throws IOException, ServletException {
    HttpServletRequest request = event.getHttpServletRequest();
    HttpServletResponse response = event.getHttpServletResponse();
    if (event.getEventType() == CometEvent.EventType.BEGIN) {
        log("Begin for session: " + request.getSession(true).getId());
        PrintWriter writer = response.getWriter();
        writer
                .println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
        writer
                .println("<head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
        writer.flush();
        synchronized (connections) {
            connections.add(response);
        }
    } else if (event.getEventType() == CometEvent.EventType.ERROR) {
        log("Error for session: " + request.getSession(true).getId());
        synchronized (connections) {
            connections.remove(response);
        }
        event.close();
    } else if (event.getEventType() == CometEvent.EventType.END) {
        log("End for session: " + request.getSession(true).getId());
        synchronized (connections) {
            connections.remove(response);
        }
        PrintWriter writer = response.getWriter();
        writer.println("</body></html>");
        event.close();
    } else if (event.getEventType() == CometEvent.EventType.READ) {
        InputStream is = request.getInputStream();
        byte[] buf = new byte[512];
        do {
            int n = is.read(buf); // can throw an IOException
            if (n > 0) {
                log("Read " + n + " bytes: " + new String(buf, 0, n)
                        + " for session: "
                        + request.getSession(true).getId());
            } else if (n < 0) {
                // error(event, request, response);
                System.out.println("you have an error");

                return;
            }
        } while (is.available() > 0);
    }
}
}

package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;

public class MessageSender implements Runnable {

protected boolean running = true;
protected ArrayList<String> messages = new ArrayList<String>();
protected ArrayList<HttpServletResponse> connections = new ArrayList<HttpServletResponse>();

public MessageSender() {
}

public void stop() {
    running = false;
}

/**
 * Add message for sending.
 */
public void send(String user, String message) {
    synchronized (messages) {
        messages.add("[" + user + "]: " + message);
        messages.notify();
    }
}

public void run() {

    while (running) {

        if (messages.size() == 0) {
            try {
                synchronized (messages) {
                    messages.wait();
                }
            } catch (InterruptedException e) {
                // Ignore
            }
        }

        synchronized (connections) {
            String[] pendingMessages = null;
            synchronized (messages) {
                pendingMessages = messages.toArray(new String[0]);
                messages.clear();
            }
            // Send any pending message on all the open connections
            for (int i = 0; i < connections.size(); i++) {
                try {
                    PrintWriter writer = connections.get(i).getWriter();
                    for (int j = 0; j < pendingMessages.length; j++) {
                        writer.println(pendingMessages[j] + "<br>");
                    }
                    writer.flush();
                } catch (IOException e) {
                    System.out.println("IOExeption sending message" + e);
                }
            }
        }

    }

}

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T05:59:24+00:00Added an answer on May 12, 2026 at 5:59 am

    Here you have a complete example for Tomcat with source code to download at the bottom:Developing with Comet and Java

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Which of the following has the best performance? I have seen method two implemented
I have implemented a python webserver. Each http request spawns a new thread. I
I have two classes, GenericList and SpecificList , where SpecificList inherits from GenericList .
I have two different Search activities implemented with SearchManager in my app. One is
I have created two classes as interface / implementation classes, and wish to pass
In a C++ program I have two classes (structs) like struct A { int
Actually, this question seems to have two parts: How to implement pattern matching? How
I have implemented what I thought was a pretty decent representation of MVC in
I have implemented a simple file upload-download mechanism. When a user clicks a file
I have implemented a SAX parser in Java by extending the default handler. The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.