não é possível transmitir no WebSocketHandlerAdapter

Estou construindo uma prova de conceito baseada na atmosfera . Criei um cliente javascript que assina 2 canais e criei uma thread no servidor que cria duas emissoras e continuo enviando dados, mas não consigo obter os dados no cliente.

Existe uma maneira de verificar se as mensagens estão ficando presas no lado do servidor ou do lado do cliente? Eu estou largando a bola em algum lugar? 🙂

Isso é o que eu tenho até agora:

PublishServerState – cria as emissoras e envia mensagem

import javax.servlet.http.HttpServlet; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.atmosphere.cpr.AtmosphereFramework; import org.atmosphere.cpr.Broadcaster; import org.atmosphere.cpr.BroadcasterFactory; // TODO desligar os threads quando a app esta desligando public class PublishServerState extends HttpServlet { private static final long serialVersionUID = 1L; public static String value1 = "um-"; public static String value2 = "dois-"; private final Logger logger = LogManager .getLogger(PublishServerState.class); private static BroadcasterFactory broadcasterFactory; public void init() { BasicConfigurator.configure(); logger.info("init()"); AtmosphereFramework framework = (AtmosphereFramework) getServletContext() .getAttribute("AtmosphereServlet"); broadcasterFactory = framework.getBroadcasterFactory(); Thread t = new Thread() { public void run() { /** * cria canais para publicacao separada, um para cada jogo */ logger.info("cria os canais"); Broadcaster canal1 = broadcasterFactory.get("/canal/1"); Broadcaster canal2 = broadcasterFactory.get("/canal/2"); logger.info("adiciona a lista"); GameSubscription.getInstance().addBroadCast("/canal/1", canal1); GameSubscription.getInstance().addBroadCast("/canal/2", canal2); long threshold = 5000; int messages = 0; long start = System.currentTimeMillis(); String time = ""; while (true) { time = Long.toString(System.currentTimeMillis()); messages ++; canal1.broadcast(new Response(value1 + time)); canal2.broadcast(new Response(value2 + time)); try { Thread.sleep(20); } catch (InterruptedException e) { logger.error("erro interrompendo thread", e); } if (System.currentTimeMillis() - start > threshold) { logger.info("broadcasting messages, sent " + messages + " messages."); messages = 0; start = System.currentTimeMillis(); } } }; }; t.start(); logger.info("start the thread"); } } 

WebSocketFacade – receba as conexões do websocket

 @WebSocketHandlerService(path = "/",broadcaster = SimpleBroadcaster.class) public class WebSocketFacade extends WebSocketHandlerAdapter{ private final Logger logger = LogManager.getLogger(WebSocketFacade.class); @Override public void onOpen(WebSocket webSocket) throws IOException { logger.info("onOpen()"); String servletPath = webSocket.resource().getRequest().getServletPath(); String pathInfo = webSocket.resource().getRequest().getPathInfo(); String canal = servletPath + pathInfo; logger.info("onOpen(), canal=" + canal ); // recebe broadcaster a partir do nome assinado Broadcaster b = GameSubscription.getInstance().getBroadCast(canal); // adiciona a conexao como um assinante // TODO verificar se eh um nome valido b.addAtmosphereResource(webSocket.resource()); } }
@WebSocketHandlerService(path = "/",broadcaster = SimpleBroadcaster.class) public class WebSocketFacade extends WebSocketHandlerAdapter{ private final Logger logger = LogManager.getLogger(WebSocketFacade.class); @Override public void onOpen(WebSocket webSocket) throws IOException { logger.info("onOpen()"); String servletPath = webSocket.resource().getRequest().getServletPath(); String pathInfo = webSocket.resource().getRequest().getPathInfo(); String canal = servletPath + pathInfo; logger.info("onOpen(), canal=" + canal ); // recebe broadcaster a partir do nome assinado Broadcaster b = GameSubscription.getInstance().getBroadCast(canal); // adiciona a conexao como um assinante // TODO verificar se eh um nome valido b.addAtmosphereResource(webSocket.resource()); } } 

poc.js – a implementação do javascript

$(document).ready(function() { console.debug('start: setup'); var socket = $.atmosphere; var status = $('#status'); var canal1 = $('#button_canal1'); var canal2 = $('#button_canal2'); var inputDados = $('#input_dados'); var buttonDados = $('#button_dados'); canal1.click(function() { console.debug('assinar canal 1'); subscribe('1'); }); canal2.click(function() { console.debug('assinar canal 2'); subscribe('2'); }); buttonDados.click(function() { console.debug('dados=' + inputDados.val()); }); console.debug('end: setup'); }); function subscribe(canal) { console.debug('subscribe : canal = ' + canal ); var request = { url : document.location.toString() + 'canal/' + canal, contentType : "application/json", logLevel : 'debug', transport : 'websocket', trackMessageLength : true, fallbackTransport : 'long-polling' }; request.onOpen = function(response) { console.debug('onOpen()'); $('#status').text('connection open'); }; request.onMessage = function(response) { console.debug('onMessage()'); var message = response.responseBody; console.debug('onMessage(), message = ' + message ); try { var json = jQuery.parseJSON(message); } catch (e) { console.log('invalid JSON: ', message); return; } $('#content-' + canal).html(json.text); }; request.onError = function(response) { console.debug('onError()'); $('#status').text('error'); }; $.atmosphere.subscribe(request); console.debug( request ); }
$(document).ready(function() { console.debug('start: setup'); var socket = $.atmosphere; var status = $('#status'); var canal1 = $('#button_canal1'); var canal2 = $('#button_canal2'); var inputDados = $('#input_dados'); var buttonDados = $('#button_dados'); canal1.click(function() { console.debug('assinar canal 1'); subscribe('1'); }); canal2.click(function() { console.debug('assinar canal 2'); subscribe('2'); }); buttonDados.click(function() { console.debug('dados=' + inputDados.val()); }); console.debug('end: setup'); }); function subscribe(canal) { console.debug('subscribe : canal = ' + canal ); var request = { url : document.location.toString() + 'canal/' + canal, contentType : "application/json", logLevel : 'debug', transport : 'websocket', trackMessageLength : true, fallbackTransport : 'long-polling' }; request.onOpen = function(response) { console.debug('onOpen()'); $('#status').text('connection open'); }; request.onMessage = function(response) { console.debug('onMessage()'); var message = response.responseBody; console.debug('onMessage(), message = ' + message ); try { var json = jQuery.parseJSON(message); } catch (e) { console.log('invalid JSON: ', message); return; } $('#content-' + canal).html(json.text); }; request.onError = function(response) { console.debug('onError()'); $('#status').text('error'); }; $.atmosphere.subscribe(request); console.debug( request ); } 

Log do lado do servidor

0 [localhost-startStop-1] INFO com.vacavitoria.atmosphere.poc.PublishServerState - init() 7 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - cria os canais 8 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - adiciona a lista 13 [localhost-startStop-1] INFO com.vacavitoria.atmosphere.poc.PublishServerState - start the thread Sep 01, 2014 12:50:22 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] Sep 01, 2014 12:50:22 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Sep 01, 2014 12:50:22 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 3739 ms 5011 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 230 messages. 5516 [http-bio-8080-exec-5] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen() 5517 [http-bio-8080-exec-5] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen(), canal=/canal/1 10027 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 228 messages. 15059 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 225 messages. 16082 [http-bio-8080-exec-6] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen() 16087 [http-bio-8080-exec-6] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen(), canal=/canal/2 20078 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 220 messages. 25085 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 222 messages.
0 [localhost-startStop-1] INFO com.vacavitoria.atmosphere.poc.PublishServerState - init() 7 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - cria os canais 8 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - adiciona a lista 13 [localhost-startStop-1] INFO com.vacavitoria.atmosphere.poc.PublishServerState - start the thread Sep 01, 2014 12:50:22 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] Sep 01, 2014 12:50:22 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Sep 01, 2014 12:50:22 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 3739 ms 5011 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 230 messages. 5516 [http-bio-8080-exec-5] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen() 5517 [http-bio-8080-exec-5] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen(), canal=/canal/1 10027 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 228 messages. 15059 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 225 messages. 16082 [http-bio-8080-exec-6] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen() 16087 [http-bio-8080-exec-6] INFO com.vacavitoria.atmosphere.poc.WebSocketFacade - onOpen(), canal=/canal/2 20078 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 220 messages. 25085 [Thread-2] INFO com.vacavitoria.atmosphere.poc.PublishServerState - broadcasting messages, sent 222 messages. 

Log do lado do cliente

start: setup poc.js:3 end: setup poc.js:28 assinar canal 1 poc.js:15 subscribe : canal = 1 poc.js:34 Invoking executeWebSocket jquery.atmosphere.js:2980 Using URL: ws://localhost:8080/atmosphere-poc/canal/1?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=2.2.3-jquery&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&Content-Type=application/json&X-atmo-protocol=true jquery.atmosphere.js:2980 Object {url: "http://localhost:8080/atmosphere-poc/canal/1", contentType: "application/json", logLevel: "debug", transport: "websocket", trackMessageLength: true…} poc.js:74 Websocket successfully opened jquery.atmosphere.js:2980 onOpen() poc.js:47 assinar canal 2 poc.js:20 subscribe : canal = 2 poc.js:34 Invoking executeWebSocket jquery.atmosphere.js:2980 Using URL: ws://localhost:8080/atmosphere-poc/canal/2?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=2.2.3-jquery&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&Content-Type=application/json&X-atmo-protocol=true jquery.atmosphere.js:2980 Object {url: "http://localhost:8080/atmosphere-poc/canal/2", contentType: "application/json", logLevel: "debug", transport: "websocket", trackMessageLength: true…} poc.js:74 Websocket successfully opened jquery.atmosphere.js:2980 onOpen()
start: setup poc.js:3 end: setup poc.js:28 assinar canal 1 poc.js:15 subscribe : canal = 1 poc.js:34 Invoking executeWebSocket jquery.atmosphere.js:2980 Using URL: ws://localhost:8080/atmosphere-poc/canal/1?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=2.2.3-jquery&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&Content-Type=application/json&X-atmo-protocol=true jquery.atmosphere.js:2980 Object {url: "http://localhost:8080/atmosphere-poc/canal/1", contentType: "application/json", logLevel: "debug", transport: "websocket", trackMessageLength: true…} poc.js:74 Websocket successfully opened jquery.atmosphere.js:2980 onOpen() poc.js:47 assinar canal 2 poc.js:20 subscribe : canal = 2 poc.js:34 Invoking executeWebSocket jquery.atmosphere.js:2980 Using URL: ws://localhost:8080/atmosphere-poc/canal/2?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=2.2.3-jquery&X-Atmosphere-Transport=websocket&X-Atmosphere-TrackMessageSize=true&Content-Type=application/json&X-atmo-protocol=true jquery.atmosphere.js:2980 Object {url: "http://localhost:8080/atmosphere-poc/canal/2", contentType: "application/json", logLevel: "debug", transport: "websocket", trackMessageLength: true…} poc.js:74 Websocket successfully opened jquery.atmosphere.js:2980 onOpen() 

Usando a resposta da pergunta: respostas Atmosphere, transmissões não chamam manipulador onMessage javascript , eu era capaz de resolver o problema! acabou de remover o trackMessageLength: true da solicitação e conseguiu ver as mensagens no cliente !!

Intereting Posts