WebSocket: OnClose() is never called

前端 未结 1 527
误落风尘
误落风尘 2021-02-13 10:31

I\'m implementing an application with a WebSocket endpoint. Here is some code:

@ApplicationScoped
@ServerEndpoint(value=\"/socket\", encoders = {MessageEncoder.c         


        
1条回答
  •  长情又很酷
    2021-02-13 11:07

    As mentioned in the comments, the code is working just fine. If we start from this wildfly-websocket-quickstart, adding an @OnClose decorated method on the ServerEndpoint, it works fine using Wildfly 10.x, and recent browsers (for instance Chrome v59.x). An example of ServerEndpoint working here (to use @Inject don't forget to add a beans.xml in WEB-INF folder):

    @ApplicationScoped
    @ServerEndpoint(value="/shout", encoders = {MessageEncoder.class})
    public class ShoutServerEndpoint {
    
        @Inject
        SessionHandler s;
    
        @OnOpen
        public void open(Session session, EndpointConfig config) throws Exception {
            s.initSession(session);
        }
    
        @OnMessage
        public void shout(String text, Session client) {
            System.out.println("Session: " + client + " has text: " + text);
            Message m = new Message();
            try {
                client.getBasicRemote().sendObject(m);//use the encoder to write some dummy message
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (EncodeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            client.getAsyncRemote().sendText(text.toUpperCase());
        }
    
    
        @OnClose
        public void onClose(Session client, CloseReason reason){
            System.out.println("Session " + client + " closing for " + reason);
            s.destroySession(client);
    
        }
    
        @OnError
        public void onError(Session session, Throwable ex) { 
            System.out.println("error: " + ex.getMessage() );
        }
    }
    

    Thus the culprit seems to be that there is an older version of the code used by wildfly that was not cleaned during a redeployment of the webapp, for instance, using Eclipse, it is worth in case of strange behavior to use the Clean option on the server used (see: this Eclipse doc)

    If deploying directly with wildfly, you can clean your resources by deleting everything in (from this article):

    • /[wildfly-location]/standalone/data
    • /[wildfly-location]/standalone/deployments
    • /[wildfly-location]/standalone/tmp

    It ensures no older copies of your code remains during a future deployment.

    0 讨论(0)
提交回复
热议问题