无法在WebSocketHandlerAdapter上播放

我正在建立一个基于氛围的websocket概念certificate。 创建了一个订阅2个频道的javascript客户端,并在服务器上创建了创建两个广播公司并继续发送数据的线程,但是我无法在客户端上获取数据。

有没有办法检查邮件是否卡在服务器端或客户端? 我在哪儿丢球吗? 🙂

这就是我现在所拥有的:

PublishServerState – 创建广播公司并发送消息

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 – 接收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 – 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 ); } 

服务器端日志

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. 

客户端日志

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() 

使用问题的回答: 大气响应,广播不调用javascript onMessage处理程序 ,我能够解决问题! 刚刚从请求中删除了trackMessageLength:true,并且能够在客户端看到消息!