使用websocket发数,有时候会发送失败。
session.getAsyncRemote().sendObject("xxx", r -> {
if (!r.isOK()) {
System.out.println("err:" + r.getException());
}
});
错误信息为:java.lang.IllegalStateException: The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method
问题原因:同一个时刻,多个线程向同一个socket写数据冲突了就会报此异常信息。
解决办法:给session加锁
synchronized (session) {
session.getAsyncRemote().sendObject("xxx", r -> {
if (!r.isOK()) {
System.out.println("err:" + r.getException());
}
});
}
websocket api 参考https://abhishek-gupta.gitbook.io/java-websocket-api-handbook/
网友评论