如何使用JEE7 Websockets将参数传递给@OnOpen方法,

Leo*_*Leo 15 java java-ee websocket

我有这个代码

@ServerEndpoint(value = "/websocket")
public class Service {
    private String clientId; 
    @OnOpen
    public void init(Session session) throws IOException {
         //opening a websocket
         // get clientId
         clientId = // Code here to get initialization parameter.
    }

}
Run Code Online (Sandbox Code Playgroud)

如何从打开套接字的客户端获取初始化参数?

Pav*_*cek 27

取决于初始化参数的含义.你可以这样做:

@ServerEndpoint(value = "/websocket/{clientId}")
public class Service {
    private volatile String clientId; 
    @OnOpen
    public void init(@PathParam("clientId") String clientId, Session session) throws IOException {
         this.clientId = clientId;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你使用以下URL来访问你的终端:ws://host/contextPath/websocket/[clientId].

如果您使用查询参数,请参阅Session#getQueryString().