Pusher:减少连接状态的超时

Pusher: Decrease timeout for connection state

我目前正在使用 Java 的 Pusher 库试验 websockets。

如果互联网连接丢失,Pusher 会自动将其连接状态从“已连接”更改为“已断开连接”。但是,这似乎只在断开连接 150 秒后才会发生。这是非常不幸的,因为在那些 150 年代,很多消息可能会丢失,并且事实上的旧消息仍然可以被视为最新消息。

我如何知道最后收到的消息是否是最新的?或者有什么方法可以减少连接状态的超时时间?

这是我正在使用的推送代码:

import com.pusher.client.Pusher;
import com.pusher.client.channel.Channel;
import com.pusher.client.channel.ChannelEventListener;
import com.pusher.client.channel.SubscriptionEventListener;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionState;
import com.pusher.client.connection.ConnectionStateChange;


public class Testing {

    public static void main(String[] args) throws Exception {


        // Create a new Pusher instance
        Pusher pusher = new Pusher("PusherKey");

        pusher.connect(new ConnectionEventListener() {

            @Override
            public void onConnectionStateChange(ConnectionStateChange change) {
                System.out.println("State changed to " + change.getCurrentState() +
                                   " from " + change.getPreviousState());
            }

            @Override
            public void onError(String message, String code, Exception e) {
                System.out.println("There was a problem connecting!");
            }
        }, ConnectionState.ALL);

        // Subscribe to a channel
         Channel channel = pusher.subscribe("channel", new ChannelEventListener() {
             @Override
             public void onSubscriptionSucceeded(String channelName) {
                 System.out.println("Subscribed!");
             }

             @Override
             public void onEvent(String channelName, String eventName, String data) {
                 System.out.println("desilo se");
             }
         });

         // Bind to listen for events called "my-event" sent to "my-channel"
         channel.bind("my-event", new SubscriptionEventListener() {
             @Override
             public void onEvent(String channel, String event, String data) {
                 System.out.println("Received event with data: " + data);
             }
         });

        while(true){
            try {
            Thread.sleep(1000);
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
            }

        }
}

}

刚刚找到答案:使用 PusherOptions 对象启动 Pusher 对象。

这里是 PusherOptions-class: http://pusher.github.io/pusher-java-client/src-html/com/pusher/client/PusherOptions.html

这是我如何将连接超时从 150 秒减少到 15 秒的简单示例:

// Define timeout parameters
PusherOptions opt = new PusherOptions();
opt.setActivityTimeout((long)10000L);
opt.setPongTimeout((long)5000L);

// Create a new Pusher instance
Pusher pusher = new Pusher(PUSHER_KEY, opt);

ActivityTimeout 定义发送 ping 以检查连接的频率,PongTimeout 定义等待 ping 信号响应的时间。

ActivityTimeout 的最小值是 1000 毫秒,但是 Pusher 强烈反对这么低的值,可能是为了减少服务器流量。