我正在尝试使用带有基于注释的客户端端点的 tyrus 独立客户端(tyrus-standalone-client-1.9)访问 websocket 服务器端点。我主要是按照这个例子。
也就是说,我的客户端端点当前看起来像
@ClientEndpoint
public class MyClientEndpoint {
private static CountDownLatch latch;
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) throws Exception {
session.getBasicRemote().sendText("initialRequest")
}
@OnMessage
public void onMessage(String message, Session session) throws Exception {
// do something
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
latch.countDown();
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
try {
URI serverEndpointUri = new URI("ws://localhost/websockets/server/endpoint");
client.connectToServer(MyClientEndpoint.class, serverEndpointUri);
latch.await();
} catch (DeploymentException | URISyntaxException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
但是,我需要将一些会话 ID 与请求一起传递,并且我需要修改请求的原始标头以使服务器端点接受我的连接。
在程序化客户端端点中,我可以做类似的事情
final Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
@Override
public void beforeRequest(final Map<String, List<String>> headers) {
headers.put("Cookie", Arrays.asList("X-Session=0f822c8c-bf63-4ae7-9d2f-af263f86baad"));
headers.put("Origin", Arrays.asList("http://localhost"));
}
});
ClientEndpointConfig clientConfig = configBuilder.build();
ClientManager client = ClientManager.createClient();
URI serverEndpointUri = new URI("ws://localhost/websockets/server/endpoint");
client.connectToServer(new MyClientEndpoint(), clientConfig, serverEndpointUri);
但是似乎没有任何选项可以将配置传递给基于注释的客户端。
是否有其他方法可以添加/修改我目前缺少的请求标头?我真的很想继续使用基于注释的方法,因为它对我来说似乎更干净......