【发布时间】:2015-02-23 11:50:47
【问题描述】:
我是 Firebase 的新手,我正在构建一个原型来测试是否适合我们的需求。我已经启动并运行了一个聊天示例,到目前为止一切都很好。
接下来是需要监听变化。我尝试使用 Java 和 JavaScript 连接到支持服务器发送事件的 REST API,但我无法使其工作。
在 Java 中我编写了以下代码:
public class FirebaseApplication {
@Test
public void test() throws Exception{
Client client = ClientBuilder.newBuilder()
.register(SseFeature.class).build();
WebTarget webTarget = client.target(new URI(
"http://incandescent-torch-xxxx.firebaseio.com/logs.json"));
EventSource eventSource = new EventSource(webTarget) {
@Override
public void onEvent(InboundEvent inboundEvent) {
System.out.println("Data " + inboundEvent.readData());
}
};
Thread.sleep(20000);
System.out.println("Exit");
eventSource.close();
}
}
然而,即使我与小程序的执行并行,我也没有收到任何事件。
接下来我尝试使用 JavaScript 客户端,但结果相同。我从来没有收到任何事件。
var source = new EventSource(
"http://incandescent-torch-xxxx.firebaseio.com/logs.json");
source.addEventListener('message', function(e) {
console.log(e.data);
}, false);
source.addEventListener('open', function(e) {
console.log("open");
// Connection was opened.
}, false);
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("close");
// Connection was closed.
}else{
console.log("error");
console.log(e);
}
}, false);
有没有人知道我做错了什么?
【问题讨论】:
-
有什么理由不能使用 Firebase 提供的 Java 客户端? firebase.com/docs/android 尽管它们经常被标记为“android 库”,但它们也适用于常规 JRE。
-
试用了它们,它们确实有效。谢谢
标签: java javascript firebase server-sent-events