1

我在我的应用程序中使用了气氛框架。

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());
    }
}
4

2 回答 2

3

You need to read the request's body by doing, in your onStateChange:

atmosphereResource.getRequest().getReader (or getInputStream). 
于 2013-03-20T14:13:11.307 回答
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);
    }
}
于 2013-03-24T15:51:02.163 回答