【发布时间】:2015-04-02 03:55:22
【问题描述】:
我想通过official Java library 使用 Pusher Websocket 连接。我运行了基本功能,例如将其连接到数据服务和接收消息。但是,我很难实现其他功能,例如读取连接状态。也许您可以通过回答以下一些问题来帮助我:
1) 启动推送器并将其连接到服务(pusher.connect()) 时会发生什么?连接的推送器是否在单独的线程中运行?
2) 如何获取推送连接的当前状态?
3) 如果我的推送器正在更新一个由其他服务并行使用的对象,这会导致问题吗?
4) 如何处理错误/异常?到目前为止我还没有收到任何错误,错误看起来像正常异常还是处理方式不同?
谢谢!
下面我复制了我当前的代码。请注意,底部的while循环仅用于测试,以便代码继续运行。
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();
}
}
}
}
}
【问题讨论】: