Created
September 29, 2010 12:24
-
-
Save guilhermesilveira/602665 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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())); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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." ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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