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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21559260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:22:50  来源:igfitidea点击:

how do I pass a parameter to the @OnOpen method with JEE7 Websockets,

javajakarta-eewebsocket

提问by Leo

I have this code

我有这个代码

@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.
    }

}

How do I get initialization parameters from the client opening the socket?.

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

采纳答案by Pavel Bucek

Depends what do you mean by initialisation parameter. You can do something like this:

取决于你所说的初始化参数是什么意思。你可以这样做:

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

Then you have do use following URL to access your endpoint: ws://host/contextPath/websocket/[clientId].

然后您必须使用以下 URL 来访问您的端点:ws://host/contextPath/websocket/[clientId]

if you use query parameters, please see Session#getQueryString().

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