用Java关闭websocket连接

时间:2015-10-26 12:42:47

标签: java java-websocket

如何使用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。

1 个答案:

答案 0 :(得分:9)

WebSocketContainer的{​​{3}}方法返回具有connectToServer Session方法的websocket two对象。这应该可以解决问题。