问题
I have a websocket endpoint as
@ServerEndpoint("/tweets")
public class TweetStreamServer {
private static final Logger LOGGER = LoggerFactory.getLogger(TweetStreamServer.class);
@OnMessage
public void tweets(final String message, final Session session) throws IOException, InterruptedException {
System.out.println("session id:" + session.getId() + ", search term: " + message);
final Client twitterClient = TwitterHoseBird.getInstance(message);
while (!session.getOpenSessions().isEmpty()) {
for (final Session s : session.getOpenSessions()) {
if (twitterClient.isDone()) {
System.out.println("Twitter Client Done, waiting ...");
}
s.getBasicRemote().sendText(TwitterHoseBird.getMsgQueue().take());
}
}
}
}
I deploy this on WildFly 8.1.0 Final
. Then I open multiple tabs on Chrome
, Safari
and run the following
var connection = new WebSocket('ws://127.0.0.1:8080/tweetstream-1.0-SNAPSHOT/tweets');
connection.onopen = function () {
connection.send('germany');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
connection.onclose = function (e) {
console.log('closing session');
};
Then all the tabs start receiving data from server.
- Then when I do
connection.close();
on one of the tabs, only that connection breaks while all the other tabs are still receiving the data - But if I close one of the tabs (in any browser), all the sessions that were open in all the other tabs close session with
closing session
message
Question
- Is it not a valid use case that if user closes a tab in one browser, all the other tabs should still receive the data?
- Do you see any bug/issue with what I am doing?
- How can I fix this issue?
Thanks
回答1:
Instead of using
s.getBasicRemote().sendText(TwitterHoseBird.getMsgQueue().take());
change it to
s.getAsyncRemote().sendText(TwitterHoseBird.getMsgQueue().take());
and everything else would just workout fine
来源:https://stackoverflow.com/questions/24741478/javaee-websocket-closing-browser-tab-closes-all-sessions-irrespective-of-browse