Sockets Netty wss套接字客户端断开连接
正在尝试设置基本Sockets Netty wss套接字客户端断开连接,sockets,websocket,kotlin,netty,wss,Sockets,Websocket,Kotlin,Netty,Wss,正在尝试设置基本wss客户端。通道被激活,但随后立即断开,无任何异常 客户: class WebSocketClient(val uri: String) { lateinit var ch: Channel fun connect() { val bootstrap = Bootstrap() val uri: URI = URI.create(uri) val handler = WebSocketClientHandler
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()
}
}
有什么遗漏吗?您忘记添加
SSLHandler
,需要此处理程序,因为您正在连接到https端口(443),因此远程服务器希望对所有流量进行加密。向https端口发送未加密的消息具有未定义的行为,某些服务器将关闭您的连接,其他服务器将重定向回https
可以使用以下方法添加sslhandler:
java:
如何使组变量?@Ferrybig更新了代码。
group
没有什么特别之处,只是创建了NioEventLoopGroup
的新实例。很好的解释!实际上,需要ssl处理程序
。谢谢
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
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())