曾经有一个bug有关websocket丢包的问题,情景是一个用户向服务器所有用户发广播,在手机端出现丢包,程序报错,在网上搜了好久没找到答案,后来同事搜了括号里的关键词,终于
在stack overflow搜到,为了防止有同样问题的小伙伴再走弯路,记一下咯
Wrap your code in a synchronized method and funnel all calls through this new method. It appears the tomcat web socket cannot handle multiple messages being placed on the same websocket session at the same time. I have code which has been running flawlessly under Glassfish and fell apart instantly when I moved to Tomcat. I then altered my code as explained above and all my problems went away....and there was much rejoicing.
意思就是tomcat上不能放置多条消息,一个用户向服务器所有用户发广播,在手机端出现丢包,程序报错,看下代码估计就懂
//广播;
public synchronized void broadcast(Object object, int wsstype, String info) {
try {
Iterator<WebSocketSession> it = WebSocketSessions.iterator();
while (it.hasNext()) {
WebSocketSession webSocketSession = it.next();
try {
if (webSocketSession.isOpen()) {
send(object, wsstype, info, webSocketSession);
} else {
it.remove();
}
} catch (Exception e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void send(Object object, int wsstype, String info, WebSocketSession webSocketSession) {
JacksonManager jm = JacksonManager.getInstance();
ObjectNode json = jm.createObjectNode();
json.put("status", 0);
json.putPOJO("info", info);
json.putPOJO("data", object);
ByteBuffer sendbb = null;
try {
sendbb = BytesCommon.changebtyes(jm.toJson(json), wsstype);
BinaryMessage binaryMessage = new BinaryMessage(sendbb);
synchronized (webSocketSession) {
webSocketSession.sendMessage(binaryMessage);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}