[websocket-client 9.3.8.RC0]로 작성된 Java Jetty 클라이언트를 사용하고 있습니다. Websocket 서버는 우리의 경우 약간 wierd입니다. 형식으로 요청을 수락합니다. WSS : //192.168.122.1 : 8443/상태 -xsrf- = tokenValueJetty Java websocket 클라이언트가 서버에 연결하지 않습니다.
토큰 값 i가 토큰 값 & Cookie 헤더를 얻을 수있는 제 로그인 POST 요청에서 수신된다. 토큰은 매개 변수로 주어 지지만 쿠키는 헤더로 추가됩니다. 이제 질문 : - 내가 아래 코드를 실행하면 시작시 awaitclose() 함수가 호출됩니다. 그러나 Onconnected 또는 Onclose와 같은 다른 기능은 없습니다.
모든 로그 또는 환경 문제를보고 소켓이 연결되지 않은 이유를 확인하려면 더 자세히 디버깅 해 주시면 감사하겠습니다.
디버깅을 위해 다음 사항을 파악하려고합니다. 1. 클라이언트 인증서가 문제를 일으키는 지 확인하려면.
내 파이썬 코드 wspy.py로 시도해도 괜찮아요.
코드
public final class websocketxxx {
WebSocketClient client=null;
public websocketxxx(){
}
public void run(String host,String cookieVal, String xsrfVal, String resource) throws IOException {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient client = new WebSocketClient(sslContextFactory);
MyWebSocket socket = new MyWebSocket();
try {
client.start();
ClientUpgradeRequest request = new ClientUpgradeRequest();
// Add the authentication and protocol to the request header
// Crate wss URI from host and resource
resource = resource + xsrfVal;
URI destinationUri = new URI("wss://" + host + resource); // set URI
request.setHeader("cookie",cookieVal);
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
//System.out.println("Request Headers print : " request.getHeaders())
System.out.println("Connecting to : " + destinationUri);
client.connect(socket, destinationUri, request);
socket.awaitClose(5000, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@WebSocket
public class MyWebSocket {
private final CountDownLatch closeLatch = new CountDownLatch(1);
@OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("WebSocket Opened in client side");
try {
System.out.println("Sending message: Hi server");
session.getRemote().sendString("Hi Server");
} catch (IOException e) {
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message from Server: " + message);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("WebSocket Closed. Code:" + statusCode);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
}
public Client getBypassCertVerificationClient() {
Client client1 = null;
try {
// Create a HostnameVerifier that overrides the verify method to accept all hosts
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String host, SSLSession sslSession) {
return true;
}
};
// Create a TrustManager
TrustManager[] trust_mgr = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t) {
}
public void checkServerTrusted(X509Certificate[] certs, String t) {
}
}
};
// Create the SSL Context
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trust_mgr, new SecureRandom());
// Create the client with the new hostname verifier and SSL context
client1 = ClientBuilder.newBuilder()
.sslContext(sslContext)
.hostnameVerifier(hostnameVerifier)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return client1;
}
public String[] simple_Login_POST_request(String host, String user, String password, String resource, String data) {
String resp = null;
String[] headers = new String[2];
try {
// Create a Client instance that supports self-signed SSL certificates
Client client = getBypassCertVerificationClient();
// Create a WebTarget instance with host and resource
WebTarget target = client.target("https://" + host).path(resource);
// Build HTTP request invocation
Invocation.Builder invocationBuilder = target.request();
// Encode the user/password and add it to the request header
invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
Form form = new Form();
form.param("userid", user);
form.param("password", password);
// Invoke POST request and get response as String
//post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Response response = invocationBuilder.method("POST", Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
resp = (String) response.readEntity(String.class);
// Print input URL, input data, response code and response
System.out.println("URL: [POST] " + target.getUri().toString());
System.out.println("HTTP Status: " + response.getStatus());
System.out.println("HTTP Status: " + response.getHeaders());
headers[0] = response.getHeaderString("Set-Cookie");
//response.getStringHeaders()
headers[1] = response.getHeaderString("X-XSRF-TOKEN");
System.out.println("Response: \n" + resp);
response.close();
} catch (Exception e) {
e.printStackTrace();
}
return headers;
}
public static void main(String[] args) throws IOException {
String host = "";
String user = "";
String password = "";
String resource = "";
host ="192.168.122.1:8443";
user = "ADMIN";
password ="ADMIN";
websocketXXX wsNotification = new websocketxxx();
/////////////////////////////////////////////////////////////////
// Simple POST LOGIN Request
resource = "/api/login";
String headers[]= wsNotification.simple_Login_POST_request(host, user, password, resource, null);
////////////////////////////////////////////////////////////////
headers[0] = headers[0].substring(headers[0].lastIndexOf(",") + 1);
System.out.println("headers[0]: " + headers[0] + "\n");
String cookie = headers[0];
String XSRFToken = headers[1];
resource = "/status?-xsrf-=";
//wsNotification.simple_websocket_example(host, cookie, XSRFToken, resource);
wsNotification.run(host, cookie, XSRFToken, resource);
}
}
변경에 따라 코드를 다음 시도했지만 아무것도 도움이되지 않았다. onConnected() 메서드가 호출되지 않습니다. 변경 사항은 다음과 같습니다 ************************ URI destinationUri = 새 URI ("wss : //"+ host + resource); // URI를 설정하십시오 \t \t \t 목록 cookies = new ArrayList (); \t \t \t cookies.add (새 HttpCookie ("Cookie", cookieVal)); \t \t \t request.setCookies (쿠키); \t \t 요청.setSubProtocols ("ao-json"); \t \t \t \t \t \t System.out.println ("Connecting to :"+ destinationUri); \t \t \t client.connect (socket, destinationUri, request); –
Ravi
'@ OnWebSocketError' 핸들러를 추가하고 websocket 레이어를 통해 어떤 종류의 에러가보고되는지 확인하십시오. –
지금은 쿠키 헤더가 문제입니다. 16 진수 코드를 제거한 후 SSH 핸드 셰이크가 출력됩니다 : no-cache..Sec-WebSocket-Protocol : ao-json 쿠키 : Cookie = "- http-session- = 4 :: http.session :: 78c7ec010a4845e5457c91546e91c3; path =/secure; httponly "...이 쿠키 헤더가 절대적으로 잘못 보았습니다. 지금 바로 고치려고 시도합니다 – Ravi