Search code examples
javawebsocketjava-websocket

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. 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?

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?

    @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.


Solution

  • Just to let anyone who is interested know, for my particular case, I put all of the implementation I needed into the onWebSocketConnect method. 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.