Jus12
Jus12

Reputation: 18024

How to run a websocket client in my Java Web App

I need to run a Java websocket client that listens to some updates from another 3rd part websocket server.

The client needs to be deployed as part of a Java webapp.

The requirement is that the client must be listening to the updates continuously.

What is the right way to do this?

I was thinking of invoking the said java code from a servlet. Is that recommended?

Edit: I have the code for the websocket (I am using Tyrus) but I am confused about the correct way to link it to my webapp. i.e., how to ensure that the websocket is running continuously.

Upvotes: 2

Views: 2517

Answers (2)

Paul Wostenberg
Paul Wostenberg

Reputation: 449

I would make it a separate class. If you want to connect and continuously listen while the application is running, you'll probably need to run it in a separate thread that kicks off when the application starts.

Threading and concurrency is a the start of a pretty deep rabbit hole, but something like a ThreadPoolExecutor with a single thread would probably work.

From there, if you're running Jetty embedded stick the Executor logic in your main method; if you're running it as a .war, you'll have to configure it to run when the web application starts.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

you can use org.eclipse.jetty.websocket:websocket-client

WebSocketClient client = new WebSocketClient();
SimpleEchoSocket socket = new SimpleEchoSocket();
try {
     client.start();
     URI echoUri = new URI(destUri);
     ClientUpgradeRequest request = new ClientUpgradeRequest();
     client.connect(socket, echoUri, request);
     System.out.printf("Connecting to : %s%n", echoUri);
     socket.awaitClose(5, TimeUnit.SECONDS);
 } catch (Throwable t) {
      t.printStackTrace();
 } finally {
    try {
         client.stop();
     } catch (Exception e) {
          e.printStackTrace();
     }
 }

Upvotes: 0

Related Questions