Skip to content

Instantly share code, notes, and snippets.

@peas
Created August 30, 2010 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peas/556995 to your computer and use it in GitHub Desktop.
Save peas/556995 to your computer and use it in GitHub Desktop.
@WebServlet(urlPatterns = { "/chat/*" }, asyncSupported=true, loadOnStartup = 1)
public class ChatServlet extends HttpServlet {
private Queue<AsyncContext> clients = new ConcurrentLinkedQueue<AsyncContext>();
private BlockingQueue<String> messages = new LinkedBlockingQueue<String>();
private int contador;
static {
System.out.println("tomcat carregou?");
}
@Override
public void init() throws ServletException {
final ExecutorService executors = Executors.newCachedThreadPool();
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
while (true) {
try {
final String message = messages.take();
for (final AsyncContext ctx : clients) {
executors.execute(new Runnable() {
@Override
public void run() {
try {
if (ctx.getResponse().isCommitted()) {
System.out.println("headers enviados ja");
}
System.out.println(ctx);
PrintWriter writer = ctx.getResponse().getWriter();
writer
.println(message);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse arg1)
throws ServletException, IOException {
System.out.println(Thread.currentThread());
System.out.println(req.isAsyncStarted());
AsyncContext ctx = req.startAsync();
ctx.setTimeout(3000000);
clients.add(ctx);
messages.add(String.format("cliente %d chegou<br/>%n", contador++));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment