简体   繁体   中英

Java websocket - close connection immediately

in my java websocket, I would like to close the connection immediately after is has been established.

Server

@ServerEndpoint(value = "/server") 
public class Server {
private static final long serialVersionUID = 1L;
private Session session;

@OnOpen
public void onOpen(Session session) throws IOException {
    System.out.println("Server Websocket open");
    this.session = session;
    try {
        session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "No Token"));
    } catch (IOException e) {
        e.printStackTrace();
    }

}


@OnMessage
public void onMessage(String message) {
    System.out.println("server receives: "+message);
}

@OnClose
public void onClose(Session session) {
    System.out.println("Server session closed");
    session = null;
}

Client

@ClientEndpoint 
public class Client {

public static void main(String[] args) {

    WebSocketContainer container = null;

    container = ContainerProvider.getWebSocketContainer();
    try {
        Session session = container.connectToServer(Client.class, URI.create("ws://localhost:8080/WebsocketServer/server"));
    } catch (DeploymentException | IOException e) {
        e.printStackTrace();
    }

}

@OnOpen
public void onOpen(Session p) {
    try {
        for (int i = 0; i < 10; i++) {
            p.getBasicRemote().sendText("Hello! ");

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        p.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@OnClose
public void OnClose() {
    System.out.println("Client connection closed");
}

Although the connection has been closed in the onOpen method at the server class, it still receives the messages from the client.

server receives: Hello! 
server receives: Hello! 
server receives: Hello! 
server receives: Hello! 
...

Why is the connection still open and receives messages, although the close method has been called?

Because gracefully closing the ws connection is an asynchronous process. Your server sends a close message, but the connection is not closed until the server has received the close reply from the client. Given your observations, it's very likely that the client has already sent the 10 'Hello!' messages before it even started to process the close message from the server. So, as far the server is concerned, the connection is still open and that's why it prints the "server receives" messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM