简体   繁体   English

用Java关闭websocket连接

[英]Close websocket connection with Java

How to close a websocket connection using Java WebSocket API? 如何使用Java WebSocket API关闭websocket连接? I have used Java websocket API for both server and client end points. 我已经将Java websocket API用于服务器端点和客户端端点。 The application is working fine. 该应用程序运行正常。 But I don't know how to close the websocket, before the main thread ends. 但是我不知道在主线程结束之前如何关闭websocket。

This is my ClientEndpoint 这是我的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();
        }
    }
}

And I use the following code to start the ClientEndPoint 我使用以下代码启动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 : I haven't used JavaScript. PS:我没有使用过JavaScript。

The WebSocketContainer 's connectToServer method returns websocket Session object that has two close methods. WebSocketContainerconnectToServer方法返回具有两个 close方法的websocket Session对象。 That should do the trick. 这应该够了吧。

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

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