netty教程2-用 channelFuture等待处理结果

[复制链接]
查看1603 | 回复0 | 2022-3-13 04:19:55 | 显示全部楼层 |阅读模式
在发起连接后,可以返回一个channelFuture用来查看链接的处理结果,5 @: d9 I" n5 D+ g; v0 [, J6 P8 x
1 使用sync方法同步处理结果' V) |) X( h6 V
2 使用addListener方法异步处理结果5 q5 v7 b/ V; a( Q* P/ @
连接成功后向服务端写个消息。
' }3 `1 H6 ]: a4 M+ ^! s代码如下:
; s( d) |* H* Y" V* x% Npackage com.study.nio.ph2;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelInitializer;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.string.StringEncoder;import lombok.extern.slf4j.Slf4j;import java.net.InetSocketAddress;/** * @program: isc-study * @description: channelFuture等待处理结果 * @author: wangjinwei * @create: 2021-10-26 10:23 **/@Slf4jpublic class EventLoopClient1 {    public static void main(String[] args) throws InterruptedException {        ChannelFuture channelFuture = new Bootstrap().group(new NioEventLoopGroup())                .channel(NioSocketChannel.class)                .handler(new ChannelInitializer<NioSocketChannel>() {                    @Override                    protected void initChannel(NioSocketChannel ch) throws Exception {                        ch.pipeline().addLast(new StringEncoder());                    }                })                .connect(new InetSocketAddress("localhost", 8080));        //1 使用sync方法同步处理结果/*        channelFuture.sync();        Channel channel = channelFuture.channel();        log.debug("{}",channel);        channel.writeAndFlush("hi 老弟");*/        log.info("channelFuture={}", channelFuture);        // 2使用addListener方法异步处理结果        channelFuture.addListener(new ChannelFutureListener() {            @Override            //在连接建立完成后会调用 operationComplete            public void operationComplete(ChannelFuture future) throws Exception {                log.info("channelFuture={}", future);                Channel channel = future.channel();                log.info("{}", channel);                channel.writeAndFlush("hi 老弟");            }        });    }}服务端代码 用 https://www.toutiao.com/i7021040158623613476/?group_id=7021040158623613476服务端代码用 netty教程1-EventLoop分工 里的代码
' t# x- {. p2 u% Z: a( p& j3 Q0 s4 P! ^2 |0 h
netty教程2-用 channelFuture等待处理结果-1.jpg

9 B& K3 B8 O9 F# `
服务端运行结果
. G" w2 ?# p% a  \$ t
8 x# u3 S' W- b8 S+ }7 ^4 B) f
netty教程2-用 channelFuture等待处理结果-2.jpg
- n! d3 \' D7 S$ @8 Y/ j% e& v
客户端运行结果
, d) j2 Z# Y" z
从客户端的运行结果看39行的channelFuture和45行的future为同一个对象
) c5 ]( Q0 C. z% I( U8 G# v+ `0 ]从客户端的运行结果来看,这个operationComplete方法里是nioEventLoopGroup里的线程运行的
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

10

金钱

0

收听

0

听众
性别

新手上路

金钱
10 元