How to get an existing websocket instance

前端 未结 2 773
礼貌的吻别
礼貌的吻别 2020-12-24 03:12

I\'m working on an application that uses Websockets (Java EE 7) to send messages to all the connected clients asynchronously. The server (Websocket endpoint) should send the

2条回答
  •  情话喂你
    2020-12-24 04:01

    Actually, WebSocket API provides a way how you can control endpoint instantiation. See https://tyrus.java.net/apidocs/1.2.1/javax/websocket/server/ServerEndpointConfig.Configurator.html

    simple sample (taken from Tyrus - WebSocket RI test):

        public static class MyServerConfigurator extends ServerEndpointConfig.Configurator {
    
            public static final MyEndpointAnnotated testEndpoint1 = new MyEndpointAnnotated();
            public static final MyEndpointProgrammatic testEndpoint2 = new MyEndpointProgrammatic();
    
            @Override
            public  T getEndpointInstance(Class endpointClass) throws InstantiationException {
                if (endpointClass.equals(MyEndpointAnnotated.class)) {
                    return (T) testEndpoint1;
                } else if (endpointClass.equals(MyEndpointProgrammatic.class)) {
                    return (T) testEndpoint2;
                }
    
                throw new InstantiationException();
            }
        }
    

    You need to register this to an endpoint:

    @ServerEndpoint(value = "/echoAnnotated", configurator = MyServerConfigurator.class)
    public static class MyEndpointAnnotated {
    
        @OnMessage
        public String onMessage(String message) {
    
            assertEquals(MyServerConfigurator.testEndpoint1, this);
    
            return message;
        }
    }
    

    or you can use it with programmatic endpoints as well:

    public static class MyApplication implements ServerApplicationConfig {
        @Override
        public Set getEndpointConfigs(Set> endpointClasses) {
            return new HashSet
              (Arrays.asList(ServerEndpointConfig.Builder
                .create(MyEndpointProgrammatic.class, "/echoProgrammatic")
                .configurator(new MyServerConfigurator())
                .build()));
        }
    
        @Override
        public Set> getAnnotatedEndpointClasses(Set> scanned) {
            return new HashSet>(Arrays.asList(MyEndpointAnnotated.class));
        }
    

    Of course it is up to you if you will have one configurator used for all endpoints (ugly ifs as in presented snippet) or if you'll create separate configurator for each endpoint.

    Please do not copy presented code as it is - this is only part of Tyrus tests and it does violate some of the basic OOM paradigms.

    See https://github.com/tyrus-project/tyrus/blob/1.2.1/tests/e2e/src/test/java/org/glassfish/tyrus/test/e2e/GetEndpointInstanceTest.java for complete test.

提交回复
热议问题