Reputation: 145
I would like to create a simple chat system with WebSocket.
If 1 user closes the connection, everything works fine and I won't get any errors but I get an error if I am connected to the server in 1 browser with multiple tabs. So if I close the browser, I get the following error:
Caused by: java.lang.IllegalStateException: Message will not be sent because the WebSocket session has been closed
@OnClose
public void handleClose(Session userSession) throws IOException {
synchronized (users) {
users.remove(userSession);
// Post the message
for (Session user : users) {
if (user.isOpen()) {
postMessage();
Data data = new Data("quit", currentTime, (String) userSession.getUserProperties().get("username"), "null", "null", new ArrayList<>(), new ArrayList<>(), "null");
if (!Objects.requireNonNull(Database.getData("SELECT * FROM users WHERE username = '" + userSession.getUserProperties().get("username") + "'", this.user)).isEmpty()) {
data = new Data("quit", this.currentTime, (String) userSession.getUserProperties().get("username"), "null", "true", new ArrayList<>(), new ArrayList<>(), "null");
}
try {
user.getBasicRemote().sendText(gson.toJson(data));
}
catch (IOException e) {
System.out.println(e.getLocalizedMessage());
}
}
}
}
}
What am I doing wrong?
Upvotes: 2
Views: 5523
Reputation: 145
I found the solution:
if (user.isOpen()) {
should be right before user.getBasicRemote().sendText(gson.toJson(data));
.
That works but I have no idea WHY it works. If you know it, please leave a comment.
Upvotes: 1
Reputation: 31
Be sure, that you observe websocket specification, especially about sending close frames look spec here.Secondly, be sure that when you check "isOpen" state, your user(one who closed page) "isOpen" state is False. And maybe, that if you're connected from multiple tabs, thats happening:
Hope It was helpful.
Upvotes: 0