use*_*232 1 java timeout websocket pusher
我目前正在使用 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();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
刚刚找到答案:使用 PusherOptions 对象启动 Pusher 对象。
这是 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);
Run Code Online (Sandbox Code Playgroud)
ActivityTimeout 定义发送 ping 来检查连接的频率,PongTimeout 定义等待 ping 信号响应的时间。
最小 ActivityTimeout 为 1000 毫秒,但是 Pusher 强烈建议不要使用如此低的值,可能是为了减少服务器流量。
| 归档时间: |
|
| 查看次数: |
2969 次 |
| 最近记录: |