我有一个客户端/服务器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);
}
}
任何建议都会受到赞赏。
答案 0 :(得分:0)
只是让任何感兴趣的人知道,对于我的特定情况,我将所需的所有实现都放入 onWebSocketConnect 方法中。 我不一定认为是一个优雅的解决方案,但它解决了我的问题。 我的应用程序非常“一次性”并且是专有的,不会在普通的客户端/服务器Web应用程序环境中推荐它。