gpt4 book ai didi

java - Pusher:减少连接状态的超时

转载 作者:行者123 更新时间:2023-11-29 03:12:54 24 4
gpt4 key购买 nike

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

如果互联网连接丢失,Pusher 会自动将其连接状态从 CONNECTED 更改为 DISCONNECTED。但是,这似乎只在断开连接 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();
}
}

}
}

}

最佳答案

刚刚找到答案:Initiate Pusher-object with PusherOptions-object。

这是 PusherOptions 类: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 强烈反对这么低的值,可能是为了减少服务器流量。

关于java - Pusher:减少连接状态的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28322020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com