Search code examples
endpointjava-websocketjsr356

How to redirect messages from one endpoint to another using java websockets (jsr 356)


I am doing a personal project to learn about java websockets. Basically my HTML clients sends messages to my server through JSR 356 websockets. The endpoint @ServerEndpoint("/wsServer") receives all messages from the clients and I would like to see those messages in another portal/endpoint @ServerEndpoint("/wsDashboard") as a dashboard in real time.

I would appreciate any idea, documentation or piece of code to start with as I really have no idea, I have seen solutions like apache kafka, but I am not sure if this is what I need.

thanks


Solution

  • Create Java Web Socket Client for /wsDashboard on onmessage method of a @ServerEndpoint("/wsServer") end point and keep it in user properties. wher you receive a message just forward the message to /wsServer web socket.

       @ServerEndpoint("/wsServer")
        public class MyWSServerEndPoint{
     @OnOpen
    public void open( Session session) {
        // Open java client websocket connection to /wsDashboard and keep the object in 
            session.getUserProperties().put("wsDashboard ", websocket);
         }
        @OnMessage
         public void onMessage(String  message,Session session){
      //forwarding the message
           session.getUserProperties().get("wsDashboard ").getRemote().send(message);
     }
        @OnClose
        public void onClose(Session session){
         session.getUserProperties().get("wsDashboard ").close();
         }
    
     }
    

    To create a client end point here is good example http://www.hascode.com/2014/11/creating-different-websocket-chat-clients-in-java/