14

如何使用 Java WebSocket API 关闭 websocket 连接?我已经将 Java websocket API 用于服务器和客户端端点。该应用程序运行良好。但我不知道如何在主线程结束之前关闭 websocket。

这是我的 ClientEndpoint

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。

4

1 回答 1

13

的方法返回具有两个关闭WebSocketContainer方法的connectToServerwebsocketSession对象。这应该够了吧。

于 2015-10-26T15:56:23.923 回答