Olá pessoal!
Tentei implementar um chat com ajax reverso baseado no tutorial da caelum e um da IBM, mas não consigo resultado satisfatório. Eu fiz um teste, abri duas abas no navegador com a página. Sendo que quando a mensagem é enviada ela aparece na página que está aberta na outra aba e vice-versa. Só aparece nas duas se enviar mais de uma vez.
@WebServlet(urlPatterns = {"/ajax"}, asyncSupported = true)
public class AjaxReversoServlet extends HttpServlet{
private List<String> lista = new ArrayList<String>();
private Queue<AsyncContext> clientes = new ConcurrentLinkedQueue<>();
@Override
public void init() throws ServletException {
Runnable r = new Runnable() {
@Override
public void run() {
while(true){
for(int i = 0; i < lista.size(); i++){
for(AsyncContext cliente : clientes){
if(lista.size() > 0){
try{
System.out.println("Clientes: " + clientes.size());
System.out.println(lista.size());
cliente.getResponse().getWriter().println(lista.get(i));
cliente.getResponse().getWriter().flush();
cliente.complete();
}catch(IOException e){
e.printStackTrace();
}
}
}
System.out.println("clear clientes");
clientes.clear();
lista.remove(i);
}
}
}
};
Thread t = new Thread(r);
t.start();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("post");
String mensagem = req.getParameter("mensagem");
lista.add(mensagem);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AsyncContext ctx;
ctx = req.startAsync();
ctx.setTimeout(10000);
ctx.addListener(new AsyncListener() {
@Override
public void onTimeout(AsyncEvent arg0) throws IOException {
clientes.remove(arg0.getAsyncContext());
}
@Override
public void onStartAsync(AsyncEvent arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void onError(AsyncEvent arg0) throws IOException {
clientes.remove(arg0.getAsyncContext());
}
@Override
public void onComplete(AsyncEvent arg0) throws IOException {
clientes.remove(arg0.getAsyncContext());
}
});
clientes.offer(ctx);
System.out.println("get clientes: " + clientes.size());
}
}
Código JS:
[code]function ajax(){
$.ajax({
cache: 'false',
url: 'ajax',
success : function(data) {
$("#mensagens").append(data);
},
});
setTimeout(function(){ajax();}, 300);
}[/code]
Obrigado à todos desde já!