问题描述
我有一个使用 JSR WebSocket 的 WebSocket 服务器,设备可以连接到该服务器。
该设备有两个版本,一些使用带有 Base64 的 TextFrames,另一些使用 Binary Frames 发送 Protobuf。
我需要两者都支持。初始 HTTP 请求中有一个标头,用于确定连接的是哪个设备。
解码器处理文件并能够将两者解码为 protobuf 消息,但是,在发送时,我希望根据连接的设备为文本或二进制文件设置编码器。
@ServerEndpoint(value = "/adapter/device",configurator = WebSocketConfig.class,decoders = { Decoders.Text.class,Decoders.Binary.class })
public class WebSocketEndpoint
{
@Onopen
public void onopen(final Session session,EndpointConfig config)
{
Version version = (Version) config.getUserProperties().get(Version.VERSION_KEY);
if (version == Version.VERSION_1)
{
config.getEncoders().add(Encoders.Text.class);
}
else
{
config.getEncoders().add(Encoders.Binary.class);
}
}
@OnClose
public void onClose(Session session)
{
System.out.println("disconnected. " + session);
}
@OnMessage
public void onMessage(Message message,Session session)
{
System.out.println("Received Msg: " + message);
}
@OnError
public void onError(Session session,Throwable thr)
{
thr.printstacktrace();
}
}
我正在尝试在运行时添加这样的编码器,但它抛出 UnsupportedOperationException,编码器/解码器的支持列表是不可修改的。
public static void sendMsg(Message msg,Session session)
{
try
{
Version version = (Version) session.getUserProperties().get(Version.VERSION_KEY);
if (version == Version.VERSION_1)
{ //text
String text = FlexBase64.encodeString(msg.toByteArray(),false);
session.getBasicRemote().sendText(text);
}
else //binary
{
session.getBasicRemote().sendBinary(ByteBuffer.wrap(msg.toByteArray()));
}
}
catch (Exception e)
{
e.printstacktrace();
}
}
有没有办法使用编码器来实现这一点?或者创建一个可以根据版本编码为文本或二进制的自定义编码器?我只想使用 session.getBasicRemote().sendobject(msg);在我的应用程序中随处可见。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)