简体   繁体   中英

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

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.

Finally with the help of Anton I solved it! First: remove static from socket() method

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

Then add an endpoint in routes file for the socket() method

GET     /ws                          controllers.HomeController.socket()

At this point you have to start the application with SSL/TLS in this way, for example:

activator run -Dhttps.port=9443

In websocket.org/echo.html insert wss://localhost:9443/ws in Location field and it connects to websocket!

Furthermore if I visit https://localhost:9443/ws I continue to obtain the message

Upgrade to WebSocket required

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM