简体   繁体   English

Java WebSocket-立即关闭连接

[英]Java websocket - close connection immediately

in my java websocket, I would like to close the connection immediately after is has been established. 在我的Java websocket中,我想在建立连接后立即关闭连接。

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. 尽管连接已在服务器类的onOpen方法中关闭,但它仍从客户端接收消息。

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? 尽管已调用close方法,但为什么连接仍保持打开状态并接收消息?

Because gracefully closing the ws connection is an asynchronous process. 因为优雅地关闭ws连接是一个异步过程。 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!' 根据您的观察,客户很可能已经发送了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. 因此,就服务器而言,连接仍处于打开状态,这就是为什么它会打印“服务器接收”消息的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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