2017-08-15 148 views
0

嘗試設置基本的wss客戶端。頻道已啓動,但立即斷開連接,無任何例外。Netty wss套接字客戶端連接失敗

客戶:

class WebSocketClient(val uri: String) { 

    lateinit var ch: Channel 

    fun connect() { 
     val bootstrap = Bootstrap() 
     val uri: URI = URI.create(uri) 
     val handler = WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, HttpHeaders.EMPTY_HEADERS, 1280000)) 

     bootstrap.group(NioEventLoopGroup()) 
       .channel(NioSocketChannel::class.java) 
       .handler(object : ChannelInitializer<SocketChannel>() { 
        override fun initChannel(ch: SocketChannel) { 
         val pipeline = ch.pipeline() 
         pipeline.addLast("http-codec", HttpClientCodec()) 
         pipeline.addLast("aggregator", HttpObjectAggregator(65536)) 
         pipeline.addLast("ws-handler", handler) 
        } 
       }) 
     ch = bootstrap.connect(uri.host, 443).sync().channel() 
     handler.channelPromise.sync() 
    } 
} 

處理程序:

class WebSocketClientHandler(val handShaker: WebSocketClientHandshaker) : SimpleChannelInboundHandler<Any>() { 

    lateinit var channelPromise: ChannelPromise 

    override fun handlerAdded(ctx: ChannelHandlerContext) { 
     channelPromise = ctx.newPromise() 
    } 

    override fun channelActive(ctx: ChannelHandlerContext) { 
     handShaker.handshake(ctx.channel()) 
    } 

    override fun channelRead0(ctx: ChannelHandlerContext, msg: Any) { 
     val ch = ctx.channel() 
     if (!handShaker.isHandshakeComplete) { 
      handShaker.finishHandshake(ch, msg as FullHttpResponse) 
      channelPromise.setSuccess() 
      return 
     } 

     val frame = msg as WebSocketFrame 
     if (frame is TextWebSocketFrame) { 
      println("text message: $frame") 
     } else if (frame is PongWebSocketFrame) { 
      println("pont message") 
     } else if (frame is CloseWebSocketFrame) { 
      ch.close() 
     } else { 
      println("unhandled frame: $frame") 
     } 
    } 
} 

處理程序的流程要求:

handleAdded 
channelRegistered 
channelActive 
channelReadComplete 
channelInactive 
channelUnregistered 
handlerRemoved 

有什麼我錯過?

+0

你如何讓你的組變量? – Ferrybig

+0

@Ferrybig更新了代碼。沒有什麼特別的關於'group',只是創建'NioEventLoopGroup'的新實例。 – eleven

回答

1

您忘了添加SSLHandler,因爲您正在連接到https端口(443),所以需要此處理程序,因此遠程服務器預計將對所有通信進行加密。向https端口發送未加密的郵件具有未定義的行爲,某些服務器將關閉您的連接,其他服務器會將重定向發送回https。

您可以通過以下方式添加sslhandler:

的java:

final SslContext sslCtx = SslContextBuilder.forClient() 
// .trustManager(InsecureTrustManagerFactory.INSTANCE) 
    .build(); 

pipeline.addLast("ssl-handler", sslCtx.newHandler(ch.alloc(), url.getHost(), 443)); 

// Your remaining code.... 
pipeline.addLast("http-codec", new HttpClientCodec()) 
+0

很好的解釋!確實需要'ssl-handler'。謝謝。 – eleven