【问题标题】:Java websocket - close connection immediatelyJava websocket - 立即关闭连接
【发布时间】:2017-03-20 02:19:30
【问题描述】:

在我的 java websocket 中,我想在建立后立即关闭连接。

服务器

@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;
}

客户

@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");
}

虽然已经在服务端类的onOpen方法中关闭了连接,但它仍然接收到来自客户端的消息。

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

为什么虽然调用了close方法,但连接仍然打开并接收消息?

【问题讨论】:

    标签: java websocket


    【解决方案1】:

    因为优雅地关闭 ws 连接是一个异步过程。您的服务器发送关闭消息,但连接不会关闭,直到服务器收到来自客户端的关闭回复。根据您的观察,客户很可能已经发送了 10 条“Hello!”。在它开始处理来自服务器的关闭消息之前的消息。因此,就服务器而言,连接仍处于打开状态,这就是它打印“服务器接收”消息的原因。

    【讨论】:

      猜你喜欢
      • 2022-07-30
      • 2018-11-09
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多