netty4 websocket client(带返回结果的客户端)

本文介绍如何使用Netty4实现一个带有返回结果的WebSocket客户端,不同于常见的HTML客户端,这个实现能够异步接收服务端返回的数据,便于业务逻辑处理。文中详细介绍了所需的pom依赖、ClientInitializer、WebSocketClientHandler和WebSocketCallable四个关键部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

netty websocket client

netty4 websocket client(带返回结果的客户端)

网上更多的基于netty的websocket服务端的实现,客户端更多的是html,本文介绍自己实现websocket的client,并返回异步返回结果的数据,方便业务逻辑调用。

pom依赖

 <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.35.Final</version>
        </dependency>
  

ClientInitializer


import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;

import java.util.concurrent.CountDownLatch;

public class ClientInitializer extends ChannelInitializer<SocketChannel> {
    private CountDownLatch latch;
    public ClientInitializer(CountDownLatch latch) {
        this.latch = latch;
    }
    private WebSocketClientHandler handler;

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        handler =  new WebSocketClientHandler(latch);
        ChannelPipeline p = sc.pipeline();
        p.addLast(new ChannelHandler[]{new HttpClientCodec(),
                new HttpObjectAggregator(1024*1024*10)});
        p.addLast("websocketHandler", handler);
    }
    public String getServerResult(){
        return handler.getResult();
    }
    public void resetLathc(CountDownLatch latch) {
        handler.resetLatch(latch);
    }
    public void setHandler(WebSocketClientHandler handler){
        this.handler = handler;
    }

WebSocketClientHandler

import io.netty.channel.*;
import io.netty.handler.codec.http.Ful

### 使用 Netty 实现 WebSocket 客户端 为了创建一个基于 NettyWebSocket 客户端,需要配置并初始化客户端引导程序 (Bootstrap),设置事件循环组 (EventLoopGroup),指定通道类型 (NioSocketChannel),并通过管道 (pipeline) 添加必要的处理器来处理连接和消息。 #### 创建 Bootstrap 并启动客户端 ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; public class WebSocketClient { private final String host; private final int port; public WebSocketClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new WebSocketClientInitializer()); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } ``` 此代码片段展示了如何通过 `Bootstrap` 设置一个新的客户端实例,并指定了用于网络 I/O 操作的线程池 `EventLoopGroup` 和要使用的通道类型 `NioSocketChannel`[^1]。 #### 配置 Pipeline 处理器 为了让客户端能够发送和接收 WebSocket 帧数据包,在建立 TCP 连接之后还需要进一步配置 `Pipeline` 来添加特定于 WebSocket 协议的消息编解码器和其他逻辑处理器: ```java import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler; public class WebSocketClientInitializer extends ChannelInitializer<SocketChannel> { private static final String WEBSOCKET_PATH = "/ws"; @Override protected void initChannel(SocketChannel ch) throws Exception { SslContext sslCtx = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build(); ChannelPipeline pipeline = ch.pipeline(); // SSL/TLS 加密支持 if (sslCtx != null && !sslCtx.isClosed()) { pipeline.addLast(sslCtx.newHandler(ch.alloc(), "localhost", 8443)); } // HTTP 编解码器 pipeline.addLast(new HttpClientCodec()); // 支持分块写入 pipeline.addLast(new ChunkedWriteHandler()); // 聚合HTTP响应对象 pipeline.addLast(new HttpObjectAggregator(8192)); // 启用压缩扩展 pipeline.addLast(new WebSocketClientCompressionHandler()); // WebSocket协议处理器 pipeline.addLast(new WebSocketClientProtocolHandler( WEBSOCKET_PATH, null, true)); // 自定义业务逻辑处理器 pipeline.addLast(new WebSocketClientHandler()); } } ``` 这段代码说明了如何向 `Pipeline` 中加入各种处理器以确保正确地解析来自服务器的数据流以及准备向外传输的信息格式。特别是加入了 `HttpClientCodec`、`HttpObjectAggregator` 及专门针对 WebSockets 的编码/解码组件 `WebSocketClientProtocolHandler`[^4]。 #### 发送与接收消息 最后一步是在自定义的 `SimpleChannelInboundHandler<String>` 子类中实现具体的读取和写出行为: ```java import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.timeout.IdleStateEvent; public class WebSocketClientHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { System.out.println("Received message from server: " + msg.text()); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { super.userEventTriggered(ctx, evt); if (evt instanceof IdleStateEvent) { // Handle heartbeat or reconnection logic here. } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } public void sendMessage(String message){ ctx.writeAndFlush(new TextWebSocketFrame(message)); } } ``` 上述实现了基本的消息监听机制,每当收到新的文本帧时就会触发相应的回调函数;同时也提供了简单的方法来进行主动的消息推送操作[^5]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值