Search code examples
websocketjava-websocket

how to identify data at the websocket url in java serverendpoint


ws://host:port/cms/ocpp/CBNO7

This is my first websocket program,here the url defines "cms" is projectname "ocpp" is serverendpoint and the last one is the data changes for every client endpoint user.How to get the last data in the server endpoint.My java serverendpoint code as follows,

`import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    import javax.ws.rs.PathParam;
    @ServerEndpoint("/ocpp")
    public class OcppWebsocketServer { 
    @OnOpen
    public void onOpen(Session session) throws IOException {
    System.out.println(session.getId() + " has opened a connection");
     try {
                session.getBasicRemote().sendText("Connection Established");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
         @OnMessage
        public void onMessage(String message, Session session) {
            System.out.println("Message from " + session.getId() + ": " + message);
        }
          @OnError
        public void onError(Throwable error) {
              System.out.println("error = " + error);
            Logger.getLogger(OcppWebsocketServer.class.getName()).log(Level.SEVERE, null, error);
        }
        @OnClose
        public void onClose(Session session) {
            System.out.println("Session " + session.getId() + " has ended");
        }
    }`

how to get CBNO7 at the endpoint


Solution

  • You need to use the PathParam: http://docs.oracle.com/javaee/7/api/javax/websocket/server/PathParam.html

    You'll end up with something like

    @ServerEndpoint("/cms/ocpp/{parameter}")
    public class OcppWebsocketServer{
    
    
         @OnMessage
         public void onMessage(@PathParam("parameter") String param, String message, Session session) {
             // it'll print CBN07
             System.out.println(param);
         }
    }
    

    Edit Make sure you import javax.websocket.server.PathParam and not the JAX-RS one