Search code examples
javasocketsplayframeworkjava-websocket

Play framework 2.5.x Web Socket Java


I am following the instructions in the official documentation of Play framework 2.5.x to Java Websockets, I created a controller with this function

public static LegacyWebSocket<String> socket() {
    return WebSocket.withActor(MyWebSocketActor::props);
}

And an Actor class MyWebSocketActor:

   public class MyWebSocketActor extends UntypedActor {

    public static Props props(ActorRef out) {
        return Props.create(MyWebSocketActor.class, out);
    }

    private final ActorRef out;

    public MyWebSocketActor(ActorRef out) {
        this.out = out;
    }

    public void onReceive(Object message) throws Exception {
        if (message instanceof String) {
            out.tell("I received your message: " + message, self());
        }
    }
}

Then the app is started I try to connect at ws://localhost:9000 as is written in the official documentation:

Tip: You can test your WebSocket controller on https://www.websocket.org/echo.html. Just set the location to ws://localhost:9000.

But the web socket seems unreachable, how can I test it?

Thanks


Solution

  • In order to handle WebSocket connections, you also have to add a route in your routes file.

    GET /ws controllers.Application.socket()

    Then your WebSocket endpoint will be ws://localhost:9000/ws - use it for testing with the echo service.