In my case, my tomcat server work with TextWebSocketHandler
.
Before doing this, you need to check this, supportsPartialMessages.
First of all, override supportsPartialMessages()
as below.
//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;
}
And then I add "messageRoom" attribute to store partial message to each websocket session when connection is established.
@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()));
}
When you get message from client, do this.
@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);
}
}
}
This is done a few years ago, so I can't remember where I got this.
But I still appreciate to them.