ws://host:port/cms/ocpp/CBNO7
这是我的第一个websocket程序,这里url定义“cms”是projectname“ocpp”是serverendpoint,最后一个是每个客户端端点用户的数据更改。如何获取服务器端点中的最后一个数据。我java serverendpoint代码如下,
`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
答案 0 :(得分:1)
您需要使用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