使用 Java 关闭 websocket 连接

Close websocket connection with Java

如何使用 Java WebSocket API 关闭 websocket 连接?我对服务器端点和客户端端点都使用了 Java websocket API。该应用程序工作正常。但是我不知道如何在主线程结束之前关闭websocket。

这是我的客户端端点

package websocket.client;

import java.io.IOException;

import javax.websocket.MessageHandler;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

@ClientEndpoint
public class EchoClient {
    Session session;

    //request
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        this.session = session;
        sendMessage("Welcome to WebSocket");
    }

    //response
    @OnMessage
    public void onMessage(String text) {
        System.out.println("Received response in client from server: " + text);
    }

    @OnError
    public void onError(Session session, Throwable t) {
        t.printStackTrace();
    }

    private void sendMessage(String message) {
        System.out.println("Sending message from client to server: " + message);
        System.out.println(session);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

然后我使用以下代码启动 ClientEndPoint

import java.io.IOException;
import java.net.URI;

import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;

import websocket.client.EchoClient;

public class WebSocketDemo {
    public static void main(String[] args) {
        String uri = "ws://localhost:8080/websocket";
        System.out.println("Connecting to " + uri);
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            container.connectToServer(EchoClient.class, URI.create(uri));
        } catch (DeploymentException | IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

PS : 我没用过 JavaScript.

WebSocketContainerconnectToServer method returns websocket Session object that has two close 方法。这应该可以解决问题。