// 连接服务端
String uri = "ws://localhost:8080/websocket";
System.out.println("Connecting to " + uri);
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(ClientSocket.class, URI.create(uri));
} catch (Exception e) {
e.printStackTrace();
}
// 客户端接收类
@ClientEndpoint
public class ClientSocket {
@OnOpen
public void onOpen(Session session) {
}
@OnMessage
public void onMessage(String message) {
}
@OnError
public void onError(Throwable t) {
}
}
ClientSocket 可能需要继承 Endpoint,具体要看使用版本的情况
session.getBasicRemote().sendText(message);
- webSocket 连接时 传递cookie 和header
public static Session connection(String uri, String cookieValue){
Session session = null;
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
ClientEndpointConfig cec = ClientEndpointConfig.Builder
.create().configurator(new ClientEndpointConfig.Configurator() {
public void beforeRequest(Map<String, List<String>> headers) {
System.out.println("Setting user cookie in beforeRequest ...");
if(null != cookieValue && !cookieValue.isEmpty()){
ArrayList<String> value = new ArrayList<>();
value.add(cookieValue);
// 设置header,
headers.put("cookie", value);
}
}
}).build();
session = container.connectToServer(ClientSocket.class, cec, URI.create(uri));
} catch (Exception e) {
e.printStackTrace();
}
return session;
}
|