玩框架 2.5.x Web Socket Java

Play framework 2.5.x Web Socket Java

我按照Play framework 2官方文档中的说明操作5.x到Java Websockets,我用这个函数创建了一个控制器

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

还有一个 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());
        }
    }
}

然后应用程序启动我尝试在 ws://localhost:9000 连接,如官方文档中所写:

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

但是web socket似乎无法访问,我该如何测试?

谢谢

为了处理 WebSocket 连接,您还必须在 routes 文件中添加路由。

GET /ws controllers.Application.socket()

然后您的 WebSocket 端点将是 ws://localhost:9000/ws - 用它来测试 echo 服务。

终于在Anton的帮助下解决了! 第一:从 socket() 方法中删除静态

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

然后在路由文件中为 socket() 方法添加一个端点

GET     /ws                          controllers.HomeController.socket()

此时你要用SSL/TLS启动应用,例如:

activator run -Dhttps.port=9443

websocket.org/echo.html 的位置字段中插入 wss://localhost:9443/ws 并连接到 websocket!

此外,如果我访问https://localhost:9443/ws,我会继续收到消息

Upgrade to WebSocket required