代码之家  ›  专栏  ›  技术社区  ›  Mahesh Mahesh.G

如何在java serverendpoint中识别websocket url上的数据

  •  1
  • Mahesh Mahesh.G  · 技术社区  · 7 年前
    ws://host:port/cms/ocpp/CBNO7
    

    `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");
            }
        }`
    

    如何在端点处获取CBNO7

    1 回复  |  直到 7 年前
        1
  •  1
  •   Al-un    7 年前

    你需要使用 PathParam : http://docs.oracle.com/javaee/7/api/javax/websocket/server/PathParam.html

    你最终会得到这样的结果

    @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);
         }
    }
    

    确保导入 javax.websocket.server.PathParam 而不是JAX-RS