【问题标题】:Java WebSocket server - push message to clientJava WebSocket 服务器 - 将消息推送到客户端
【发布时间】:2017-02-17 14:18:03
【问题描述】:

我有一个客户端/服务器 websocket 解决方案,但非常规,我希望服务器在未启动的情况下将更新推送到客户端。 在发送更新时,我还想避免使用某种间隔计时器,而是让它们由服务器端事件触发。

我看到问题已经在这里提出,但似乎没有人有一个优雅的解决方案。

How to implement push to client using Java EE 7 WebSockets?

在同一个解决方案中,用户提供了类似于以下的建议,但我想知道如何从另一个类调用 sendMessage(String message) 方法?

    @WebSocket
    public static class EchoSocket
    {
        private org.eclipse.jetty.websocket.api.Session session;
        private org.eclipse.jetty.websocket.api.RemoteEndpoint remote;

        @OnWebSocketClose
        public void onWebSocketClose(int statusCode, String reason)
        {
            this.session = null;
            this.remote = null;
            System.out.println("WebSocket Close: {} - {}" + statusCode + " : " + reason);
        }

        @OnWebSocketConnect
        public void onWebSocketConnect(org.eclipse.jetty.websocket.api.Session session)
        {
            this.session = session;
            this.remote = this.session.getRemote();
            System.out.println("WebSocket Connect: {}" + session.toString());
            this.remote.sendStringByFuture("You are now connected to " + this.getClass().getName());
        }

        @OnWebSocketError
        public void onWebSocketError(Throwable cause)
        {
            System.out.println("WebSocket Error" + cause.getLocalizedMessage());
        }

        @OnWebSocketMessage
        public void onWebSocketText(String message)
        {
            if (this.session != null && this.session.isOpen() && this.remote != null)
            {
                System.out.println("Echoing back text message [{}]" + message);
                this.remote.sendStringByFuture(message);
            }
        }

        public void sendMessage(String message) {
            this.remote.sendStringByFuture(message);
        }

    }

任何建议将不胜感激。

【问题讨论】:

    标签: java websocket java-websocket


    【解决方案1】:

    只是为了让感兴趣的人知道,对于我的特殊情况,我将我需要的所有实现都放入了 onWebSocketConnect 方法中。 我不一定认为这是一个优雅的解决方案,但它为我解决了这个问题。 我的应用程序非常“一次性”并且是专有的,因此不建议在普通的客户端/服务器 Web 应用程序上下文中使用它。

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 1970-01-01
      • 2018-10-25
      • 2019-11-12
      • 1970-01-01
      • 2011-04-02
      • 2016-02-24
      • 2012-04-11
      • 2022-07-15
      相关资源
      最近更新 更多