Skip to content

Instantly share code, notes, and snippets.

@guilhermesilveira
Created September 29, 2010 12:24
Show Gist options
  • Select an option

  • Save guilhermesilveira/602665 to your computer and use it in GitHub Desktop.

Select an option

Save guilhermesilveira/602665 to your computer and use it in GitHub Desktop.
private BlockingQueue<String> messages = new LinkedBlockingQueue<String>();
private AtomicInteger counter = new AtomicInteger();
protected void doPost(HttpServletRequest req, HttpServletResponse arg1)
throws ServletException, IOException {
System.out.println("sending a message to all clients");
messages.add(String.format("sending message number %d %n", counter.incrementAndGet()));
}
private Queue<AsyncContext> clients = new ConcurrentLinkedQueue<AsyncContext>();
protected void doGet(HttpServletRequest req, HttpServletResponse arg1)
throws ServletException, IOException {
AsyncContext ctx = req.startAsync();
ctx.setTimeout(3000000);
clients.add(ctx);
System.out.println("new client connected." );
}
public void run() {
while (true) {
final String message = messages.take();
for (final AsyncContext ctx : clients) {
public void run() {
PrintWriter writer = ctx.getResponse().getWriter();
writer.println(message);
writer.flush();
}
}
}
}
@WebServlet(urlPatterns = { "/subscribe" }, asyncSupported = true)
public class ChatServlet extends HttpServlet {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment