Java EE Websocket编程端点如何使用Pathparams?

时间:2018-07-28 20:08:43

标签: java websocket glassfish endpoint

我对Java EE还是很陌生,所以如果我的要求对您没有意义,请不要对我苛刻。我遵循了一些有关实现websocket api的教程,实质上创建了两个类。首先是这样的终结点类:

public class ChatEndpoint extends Endpoint {
    private static final ConcurrentLinkedQueue<Session> peers = new ConcurrentLinkedQueue<>();
    private static final Logger LOGGER = Logger.getLogger(ChatEndpoint.class.getName());

    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        LOGGER.log(Level.INFO, "New session opened");
        peers.add(session);

        session.addMessageHandler(new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String message) {
                LOGGER.log(Level.INFO, String.format("Received message: %s", message));
                try {
                    broadcastMessage(message, session);
                } catch (IOException e) {
                LOGGER.log(Level.SEVERE, null, e);
                }
            }
        });
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        LOGGER.log(Level.INFO, String.format("Session closed with reason %s", closeReason.getReasonPhrase()));
    }

    public void broadcastMessage(String message, Session session) throws IOException {
        for (Session peer : peers) {
            peer.getBasicRemote().sendText(message);
        }
    }
}

...以及我的配置类:

public class ServerConfig implements ServerApplicationConfig {
    @Override
    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
        Set<ServerEndpointConfig> results = new HashSet<>();

        for (Class endpointClass : endpointClasses) {
            if (endpointClass.equals(ChatEndpoint.class)) {
                ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(endpointClass, "/chat").build();
                results.add(serverEndpointConfig);
            }
        }
        return results;
    }

    @Override
    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> endpointClasses) {
        return Collections.emptySet();
    }
}

现在您可以看到,我采用了程序化而非注释方式。我知道使用注释的部署方式,可以指定路径参数,然后从客户端从onMessage中接收路径参数。那么这如何与程序化端点部署一起工作?

0 个答案:

没有答案