gpt4 book ai didi

javascript - Atmosphere :服务器收到消息

转载 作者:行者123 更新时间:2023-12-03 06:57:36 25 4
gpt4 key购买 nike

我有一个带有 onMessage 函数的 ManagedService

@ManagedService(path = "/atmosphere/formuserpresence/{id}")
public class FormUserPresenceUpdate extends AtmosphereHelper
{

@Message
public final void onMessage(final String message) throws IOException
{
...
...
...
...
broadcast(FormUserPresenceUpdate.class, "/atmosphere/formuserpresence/" + statusMessage.getId(), returnArrayString);
}

}

我有客户端-服务器通信。多个客户端可以使用他们的 ID 订阅该 channel 。然后,客户端可以发送状态,例如

消息 = { 身份:“唯一ID”, 状态:“状态消息值” });

类 FormUserPresenceUpdate 存储所有接收到的所有客户端状态,并通过广播函数将它们作为数组作为消息发送回来(returnArrayString)。

问题在于,无论客户端收到正确的值(消息数组),服务器也会从自身接收到该数组,但无法解析它。那么,问题来了:针对这种情况,有什么解决办法呢?我可以以某种方式做到这一点,而不是由服务器本身发送这组消息吗?或者我应该创建第二个 channel (我真的不想这样做)?

最佳答案

您应该将消息定义为一个类,并为该类定义一个解码器;)

public class Message {
private String ident;
private String status;
...

getter and setter method.

...
}

解码器(这取决于com.fasterxml.jackson.databind.ObjectMapper):

public class MessageDecoder implements Decoder<String, Message> {

private ObjectMapper mapper = new ObjectMapper();

@Override
public Message decode(String s) {
try {
return mapper.readValue(s, Message.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

并将decoders = {MessageDecoder.class}添加到@Message:

@Message(decoders = {MessageDecoder.class})
public final void onMessage(final String message) throws IOException
{
...
...
...
...
broadcast(FormUserPresenceUpdate.class, "/atmosphere/formuserpresence/" + statusMessage.getId(), returnArrayString);
}

还有另一种解决方案,使用JSONParser来判断消息是否可以解析为Message类,如果不能,则让@Messsage方法返回。

关于javascript - Atmosphere :服务器收到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37206792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com