无法在WebSocketHandlerAdapter上播放 [英] not able to get broadcast on WebSocketHandlerAdapter

查看:180
本文介绍了无法在WebSocketHandlerAdapter上播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a websocket proof of concept based on atmosphere. Created a javascript client that subscribes to 2 channels, and created thread on the server that creates two broadcasters and keep sending data to then, but I'm not able to get the data on the client.

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

Is there a way to check if the messages are getting stuck on the server side or client side ? Am I dropping the ball somewhere ? :)

这就是我现在所拥有的:

This is what I have until now :

PublishServerState - 创建广播公司和发送消息

PublishServerState - create the broadcasters and send message


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连接

WebSocketFacade - receive the websocket connections



@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实现

poc.js - the javascript implementation



$(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.

客户端日志



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,并且能够在客户端看到消息!!

Using the response from the question : Atmosphere responses, broadcasts do not call javascript onMessage handler, I was able to solve the problem !! just removed the trackMessageLength : true from the request and was able to see the messages at the client !!

这篇关于无法在WebSocketHandlerAdapter上播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆