2

我一直在努力寻找一种使用 Autobahn for android 实现 PubSub 的好方法。我目前正在使用 Singleton 模式在我的整个应用程序中使用相同的 AutobahnConnection。我接到电话和订阅工作但是当我取消订阅然后回到同一个片段并尝试再次订阅时它不起作用。在我目前的高速公路班下面:

package nl.w3s.hulpverlener.utils;

import nl.w3s.hulpverlener.helper.DebugHelper;
import android.util.Log;
import de.tavendo.autobahn.Autobahn;
import de.tavendo.autobahn.Autobahn.SessionHandler;
import de.tavendo.autobahn.AutobahnConnection;
import de.tavendo.autobahn.AutobahnOptions;

public final class AutobahnService{
    private static AutobahnService INSTANCE;
    private static AutobahnConnection connection;

    private AutobahnOptions options;
    private boolean connected = false;

    private String url = "http://johelpen.w3s.nl/";
    private String websocketUrl;

    private AutobahnService() {
        connection  = new AutobahnConnection();
        options = new AutobahnOptions();
        options.setReceiveTextMessagesRaw(true);

        websocketUrl = CommonUtilities.STAGING_WEBSOCKET_URL;
        connect();
    }

    public static AutobahnService getInstance() {
        if(INSTANCE == null)
            INSTANCE = new AutobahnService();
        else
            INSTANCE.connect();

        return INSTANCE;
    }

    public void connect() {
        if(!connection.isConnected()) {
            connection.connect(websocketUrl, new SessionHandler() {
                @Override
                public void onOpen() {
                    connected = true;
                    Log.i(DebugHelper.TAG_DEBUG, "CONNECTED");
                }

                @Override
                public void onClose(int p_intCode, String p_strReason) {
                    connected = false;
                    Log.i(DebugHelper.TAG_DEBUG, "DISCONNECTED");
                }
            }, options);
        }
    }

    public void doCall(final String callType, final Class<?> classRef, final Autobahn.CallHandler autobahnEventHandler, final Object... arguments) {
        connection.call(url + "#" + callType, classRef, autobahnEventHandler, arguments);
    }

    public void doSubscribe(final String callType, final Class<?> classRef, final Autobahn.EventHandler autobahnEventHandler) {
        connection.subscribe(url + callType, classRef, autobahnEventHandler);
    }

    public void doUnsubscribe(final String callType) {
        connection.unsubscribe(url + callType);
    }
}

当我查看我的日志时,它在取消订阅和重新订阅时不会断开连接。

4

0 回答 0