13

I want to create a websocket endpoint client in Java (as pure as possible, no frameworks), but virtually all the examples I have found have only server endpoints in Java, whereas the client is in Javascript. Can anyone point me to a good client example, or provide one?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
  • Why do you care about websockets if your client is Java? Are you interfacing with an existing server which only provides a websocket API? And why no libraries? – Matt Ball Feb 17 '14 at 20:49
  • 1
    That is correct, I want to connect to a websocket server. Libraries are fine, I just prefer to focus on core libraries, preferably from Oracle only, and not be adding a bunch of jars from some fly-by-night third party or random github developer unbacked by a major company. – Tyler Durden Feb 17 '14 at 20:52
  • User Tyrus a java web socket standalone client. - https://tyrus.java.net/ – Sathish Kumar k k Jun 16 '15 at 15:14
  • I nominate this question for re-opening since it is a Famous Question. – Tyler Durden Mar 03 '16 at 16:05

2 Answers2

10

@ClientEndpoint annottation is part of the spec, so I'd suggest to use that, here is a good tutorial , see step 4 and 6 .

Step 6 from Openshift tutorial

 @ClientEndpoint
public class WordgameClientEndpoint {

private static CountDownLatch latch;

private Logger logger = Logger.getLogger(this.getClass().getName());

@OnOpen
public void onOpen(Session session) {
    // same as above
}

@OnMessage
public String onMessage(String message, Session session) {
    // same as above
}

@OnClose
public void onClose(Session session, CloseReason closeReason) {
    logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
    latch.countDown();
}

public static void main(String[] args) {
    latch = new CountDownLatch(1);

    ClientManager client = ClientManager.createClient();
    try {
        client.connectToServer(WordgameClientEndpoint.class, new URI("ws://localhost:8025/websockets/game"));
        latch.await();

    } catch (DeploymentException | URISyntaxException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}

}

in this example they are using tyrus, which is the reference implementation for websockets in java, so I think that meets your requirement of a well backed websocket implementation.

Leo
  • 1,829
  • 4
  • 27
  • 51
6

Not sure if this fits your criteria, but Jetty has a pretty clean client example here:

http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html

Hope that helps :)

lorinpa
  • 556
  • 1
  • 5
  • 6