nettywebsocket客户端示例

egmofgnx  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(290)

我有client.p12文件和mypassword,我正在尝试使用netty代码建立websocket连接。目前我在okhttpclient中有一个工作示例。但我很难将其Map到netty。
我的服务器给了我要连接的域“https://api.server.com"
在okhttpclient中,以下代码起作用

OkHttpClient client = getClient(info);
    Request request = new Request.Builder().url("https://api.server.com" + "/messaging").build();
    WebSocket webSocket = client.newWebSocket(request, listener);

这里的getclient代码如下:

public static OkHttpClient getClient(ConnectionInfo info) {

      KeyStore appKeyStore = KeyStore.getInstance("PKCS12");
      appKeyStore.load(new FileInputStream("client.p12"), "MyPassword".toCharArray());
      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
      keyManagerFactory.init(appKeyStore, info.getPassword().toCharArray());

      TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
      trustManagerFactory.init((KeyStore) null);
      TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

      if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException(
              "Unexpected default trust managers:" + Arrays.toString(trustManagers));
      }

      X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, new TrustManager[] {trustManager}, null);
      context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

      OkHttpClient.Builder builder =
        new OkHttpClient.Builder().sslSocketFactory(context.getSocketFactory(), trustManager);

      builder.retryOnConnectionFailure(true);

      return builder.build();
  }

现在上面的代码运行良好,我正在尝试在netty中实现它。所以看看示例代码,它只接受协议 ws 以及 wss . 而在上面的示例中,https请求使用适当的头升级到websocket。所以我的理解是,如果我提供域名为“wss:///api.server.com/messaging”,那么它将首先建立https连接,然后将其升级到websocket。
现在我不知道如何设置证书和密码。

// I have created a keyStore as following
    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client.p12"));
    try {
      keyStore.load(instream, "MyPassword".toCharArray());
    } finally {
      instream.close();
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
     // How to specify the above keystore with this client?
      sslCtx = SslContextBuilder.forClient()
        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
      sslCtx = null;
    }
pengsaosao

pengsaosao1#

SSlContextBuilder 有一种方法 KeyManagerFactory :

SslContextBuilder.forClient()
    .keyManager(keyManagerFactory)
    .trustManager(InsecureTrustManagerFactory.INSTANCE)
    .build();

相关问题