在Spring-Websockets 4.2中使用SockJS的部分消息

Jan*_*Jan 16 spring sockjs spring-websocket

我正在使用带有SockJS的Spring-Websockets 4.2.

由于客户端收到的消息可能非常大,我想使用部分消息.我的TextWebSocketHandler的子类确实覆盖supportsPartialMessages以返回true.但是,由于Spring创建的SockJsWebSocketHandler不支持部分消息,我仍然会收到错误code=1009, reason=The decoded text message was too big for the output buffer and the endpoint does not support partial messages.

作为一种变通方法,如描述我增加了缓冲区大小为1 MB 这里,但因为我要支持相当大量的客户端(〜2000年在同一时间),这需要太多的内存.

有没有办法使用SockJS的部分消息?

jor*_*han 1

就我而言,我的 tomcat 服务器使用TextWebSocketHandler.
在执行此操作之前,您需要检查supportsPartialMessages

首先,supportsPartialMessages()按如下方式覆盖。

//This value set as true in my properties file. Just for test. actually you don't need this.
@Value("#{config['server.supportsPartialMessages']}")
private boolean supportsPartialMessages;

//If you need to handle partial message, should return true.
@Override
public boolean supportsPartialMessages() {
    return supportsPartialMessages;     
}
Run Code Online (Sandbox Code Playgroud)

然后我添加“messageRoom”属性,以便在建立连接时将部分消息存储到每个 websocket 会话。

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    super.afterConnectionEstablished(session);

    //I think this is easier to keep each message and each client.
    session.getAttributes().put("messageRoom", new StringBuilder(session.getTextMessageSizeLimit()));
}
Run Code Online (Sandbox Code Playgroud)

当您收到客户的消息时,请执行此操作。

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    super.handleTextMessage(session, message);

    StringBuilder sbTemp = (StringBuilder)session.getAttributes().get("messageRoom");

    //isLast() will tell you this is last chunk or not.
    if(message.isLast() == false) {     
        sbTemp.append(Payload);

    }else {
        if(sbTemp.length() != 0) {          
            sbTemp.append(Payload);     

            this.logger.info(session.getRemoteAddress() + ":RECEIVE_TO[CLIENT][PARTIAL][" + sbTemp.length() + "]:" + sbTemp.toString());
            doYourWork(session, sbTemp.toString());
            //Release memory would be nice.
            sbTemp.setLength(0);
            sbTemp.trimToSize();

        }else {         
            this.logger.info(session.getRemoteAddress() + ":RECEIVE_TO[CLIENT][WHOLE]:" + message.getPayload());
            doYourWork(session, Payload);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是几年前做的,所以我不记得我从哪里得到的。但我还是很感谢他们。