Created
August 30, 2010 03:46
-
-
Save peas/556995 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
@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