Tomcat 8 getOpenSessions()没有为终点返回所有会话? [英] Tomcat 8 getOpenSessions() not returning all sessions for end point?

查看:470
本文介绍了Tomcat 8 getOpenSessions()没有为终点返回所有会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发我的第一个WebSocket应用程序,当这样的代码不能始终如一地工作时,我感到很惊讶:

I'm working on my first WebSocket app, and was surprised when code like this did not work consistently:

@ServerEndpoint(value="/msg/{owner}", encoders=MessageEncoder.class, decoders=MessageEncoder.class)
public class WebSocketListener {

    public WebSocketListener() {
    }

    @OnOpen
    public void open(Session session, @PathParam("owner") String owner) {
        if (session.getUserPrincipal() != null) {
            session.getUserProperties().put("owner", owner);
        }
        else {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Not authorized"));
            } catch (IOException e) {
            }
        }
    }

    @OnClose
    public void close(Session session) {
    }

    @OnError
    public void onError(Throwable error) {
    }

    @OnMessage
    public void onMessage(final Session session, final Message message) {
        String owner = (String)session.getUserProperties().get("owner");
        for (Session s:session.getOpenSessions() {
            System.out.println(s);
            if (s.isOpen() && owner.equals(s.getUserProperties().get("owner"))) {
                s.getAsyncRemote().sendObject(message);
            }
        }
    }

}

从两个客户端和同一个所有者连接到此终点时,我观察到的是有时两个会话都是从getOpenSession()返回的,但通常不会返回该用户的会话,如System.out.println所示。我的解决方法是通过向此类添加静态映射来使用getOpenSessions,添加使用所有者作为密钥的列表会话,只是使用它。但这是一个已知的错误,我找不到任何人抱怨这个搜索?

What I observe when connecting to this end point from two clients and the same 'owner', is that sometimes both sessions are returned from getOpenSession(), but more often than not only that user's session is returned, as evidenced by the System.out.println. My workaround was to ditch using getOpenSessions by adding a static map to this class, adding the session to a list using the owner as the key, and just using that instead. But is this a known bug, I couldn't find anyone complaining about this from searching?

推荐答案

它似乎是tomcat中的一个bug,我遇到了与嵌入式tomcat相同的问题Spring Boot,将服务器更改为Jetty解决了这个问题。在Spring Docs中,有一节解释了如何切换服务器: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-jetty-instead-of-tomcat

it seems to be a bug in tomcat, I faced the same issue with embedded tomcat in Spring Boot, changing the server to Jetty resolved the issue. In Spring Docs, there is a section explaining how to switch the server: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-jetty-instead-of-tomcat

这篇关于Tomcat 8 getOpenSessions()没有为终点返回所有会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆