1

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.

theapache64
  • 10,926
  • 9
  • 65
  • 108

2 Answers2

3

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.

Community
  • 1
  • 1
Takahiko Kawasaki
  • 18,118
  • 9
  • 62
  • 105
  • Wow, but how can i get the `JAR` version of that library @Takahiko Kawasaki – theapache64 Aug 28 '15 at 15:07
  • If you are using Maven or Gradle, read [README.md](https://github.com/TakahikoKawasaki/nv-websocket-client/blob/master/README.md). Otherwise, download a JAR file from [here](https://repo1.maven.org/maven2/com/neovisionaries/nv-websocket-client/). – Takahiko Kawasaki Aug 28 '15 at 15:18
1

To answer your question #1... YES!

Client library: Jetty

Example: Stack Overflow Example 26452903

However, I would suggest maybe rethink the communication protocol you may be using. You could utilize some other protocol that provides the most benefit based on the solution you are employing. Just food for thought.

Community
  • 1
  • 1
Andrew
  • 381
  • 1
  • 7