Search code examples
javawebsocketjava-websocket

How can i connect to a WebSocket from a Java console program?


I am new in Java. I've created a simple WebSocket.

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;


@ServerEndpoint("/RankixSocket")
public class RankixSocket {

    @OnOpen
    public void onOpen(Session session) {
        try {
            session.getBasicRemote().sendText("Connected");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("New message : " + message);
        try {
            session.getBasicRemote().sendText("Message received -> :" + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose() {
        System.out.println("Closed");
    }

}

Now i want to connect to the WebSocket from the console application. I've seen an example of connecting to the WebSocket from Android Application. In that example the author used an external library. I've googled a lot but nothing found helpful :( .

  1. Is it possible to connect to a WebSocket from a normal Java console application ? then How can i do that? Is there any external libraries ?

Any help will be appreciated.


Solution

  • EchoClient.java is a simple console application which connects to ws://echo.websocket.org. The application uses nv-websocket-client library. What you should consider when selecting a WebSocket client library for Java are listed here.