我在我的应用程序中使用氛围框架。
https://github.com/Atmosphere/atmosphere
我扩展了AbstractReflectorAtmosphereHandler类并实现了
-onRequest
-destroy
-onstatechanged
方法
当客户想要向服务器发送消息时:
subSocket.push(jQuery.stringifyJSON({ data: "blahblah", source:"client" }));
调用onRequest函数;但是消息
Object message = atmosphereResource.getAtmosphereResourceEvent().getMessage();
是空的。
我尝试使用每次调用的onstatechanged
(1) The remote connection gets closed, either by a browser or a proxy
(2) The remote connection reach its maximum idle time (AtmosphereResource.suspend))
(3) Everytime a broadcast operation is executed (broadcaster.broadcast)
然而,即使过滤掉1和2
public void onStateChange(AtmosphereResourceEvent event)
throws IOException {
if (source.equals("client") && !event.isResumedOnTimeout() && !event.isResuming()){
System.out.println("message form client");
System.out.println(message.toString());
} else {
//normal onstatechanged code from AbstractReflectorAtmosphereHandler
}
然而,消息随机打印2至4次。它应该只被调用一次。
所以我的问题是:我可以在onRequest方法中访问该消息,或者为什么onStateChange被调用了这么多次。
编辑:从jF给出的答案我已经能够访问onRequest函数内的消息。 (但我不确定这是否是他实际的意思)。
public void onRequest(AtmosphereResource resource) throws IOException {
//Object message = resource.getAtmosphereResourceEvent().getMessage(); //is empty why?
//leave connection open
resource.suspend();
BufferedReader reader = resource.getRequest().getReader();
Object message = reader.readLine();
if (message !=null){
System.out.println("**onRequest: "+message.toString());
}
}
答案 0 :(得分:3)
萨吕,
你需要在你的onStateChage中读取请求的正文
atmosphereResource.getRequest()。getReader(或getInputStream)。
- Jeanfrancois
答案 1 :(得分:1)
也许这有助于其他人:
public void onRequest(AtmosphereResource resource) throws IOException {
//Object message = resource.getAtmosphereResourceEvent().getMessage(); //is empty why?
//leave connection open
resource.suspend();
BufferedReader reader = resource.getRequest().getReader();
Object message = reader.readLine();
if (message !=null){
Object obj = JSONValue.parse(message.toString());
JSONObject jsonObject = (JSONObject) obj;
Object source = jsonObject.get("source");
System.out.println("**onRequest: "+message.toString());
ArrayList frame = new ArrayList();
frame.add(jsonObject.get("type"));
frame.add(jsonObject.get("data"));
writeQueue.add(frame);
}
}