14

How to close a websocket connection using Java WebSocket API? I have used Java websocket API for both server and client end points. The application is working fine. But I don't know how to close the websocket, before the main thread ends.

This is my 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

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.

1 Answer 1

14

The WebSocketContainer's connectToServer method returns websocket Session object that has two close methods. That should do the trick.

1
  • 1
    I'll try it out. Can I also use the Session object that is passed as a parameter to the onOpen method of @ClientEndpoint to close a connection ?
    – UnahD
    Commented Oct 27, 2015 at 5:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.