[英]Java WebSocket server - push message to client
I have a client/server websocket solution in place but rather unconventionally, I would like for the server to push update to the client, uninitiated. 我有一个客户端/服务器Websocket解决方案,但非常规地,我希望服务器将更新未启动地推送到客户端。 In sending updates, I would also like to avoid the use of some sort of interval timer but rather have them triggered by a server side event. 在发送更新时,我还希望避免使用某种间隔计时器,而是让它们由服务器端事件触发。
I see the question has already been posed here but no one appears to have an elegant solution. 我看到这里已经提出了问题,但似乎没有人提出一个优雅的解决方案。
How to implement push to client using Java EE 7 WebSockets? 如何使用Java EE 7 WebSockets实现对客户端的推送?
In the same solution a user offers a suggestion similar to the following, but I'm wondering how to call the sendMessage(String message) method from another class? 在相同的解决方案中,用户提供与以下内容类似的建议,但我想知道如何从另一个类调用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);
}
}
Any suggestions would be mucho appreciated. 任何建议将不胜感激。
Just to let anyone who is interested know, for my particular case, I put all of the implementation I needed into the onWebSocketConnect method. 为了让感兴趣的任何人知道,对于我的特殊情况,我将所需的所有实现都放入onWebSocketConnect方法中。 I don't necessarily think is an elegant solution but it solved the problem for me. 我不一定认为这是一个优雅的解决方案,但它为我解决了这个问题。 My application was quite "once off" and proprietary and would not recommend it in a normal client/server web application context. 我的应用程序相当“一次性”且专有,因此不会在普通的客户端/服务器Web应用程序上下文中推荐它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.