How do you read/receive messages from a websocket stream in Java?

Viewed 294

So I just started experimenting with Websockets. All I want to do is read messages from this Websocket stream. I've created a simple Spring Application just to get started, but I'm unable to receive/read any messages from the stream. The handshake is successful (what I can glean from the logs). Here's what it looks like - please forgive the crappy code, I'll be working on that one I got the basics working.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.OnMessage;
import java.net.URI;
import java.util.concurrent.ExecutionException;

@SpringBootApplication
public class DemoApplication extends TextWebSocketHandler {

    private WebSocketSession clientSession;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received msg: "+message);
    }
    public DemoApplication () throws ExecutionException, InterruptedException {
        StandardWebSocketClient webSocketClient = new StandardWebSocketClient();
        this.clientSession = webSocketClient.doHandshake(this, new WebSocketHttpHeaders(),
                URI.create("wss://hostname.com/")).get(); 

        System.out.println("HANDSHAKE DONE!!!");
    }

}

From what I've read on tutorials so far, the @OnMessage is triggered when the application receives messages, right? But my @OnMessage is never triggered. Am I missing something fundamentally here? I'm really, really new to this!

0 Answers
Related