netty客户端同步请求实现

netty客户端同步请求实现

客户端 SimpleChatClientHandler

package com.netty.chart;

import java.util.concurrent.CountDownLatch;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class SimpleChatClientHandler extends SimpleChannelInboundHandler<String> {

    private CountDownLatch lathc;

    public SimpleChatClientHandler(CountDownLatch lathc) {
        this.lathc = lathc;
    }

    private String result;

    @Override
    protected void channelRead0(ChannelHandlerContext arg0, String arg1) throws Exception {
        System.out.println("==========收到服务器消息:"+arg1);
        result = arg1;
        lathc.countDown();//消息收取完毕后释放同步锁
    }

    public void resetLatch(CountDownLatch initLathc){
        this.lathc = initLathc;
    }

    public String getResult() {
        return result;
    }

     @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // IdleStateHandler 所产生的 IdleStateEvent 的处理逻辑.
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case ALL_IDLE:
                    handleAllIdle(ctx);
                    break;
                default:
                    break;
            }
        }
    }

    protected void handleAllIdle(ChannelHandlerContext ctx) {
//        ctx.channel().writeAndFlush("1" + "\r\n");
    }

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

客户端 SimpleChatClientInitializer

package com.netty.chart;

import java.util.concurrent.CountDownLatch;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class SimpleChatClientInitializer extends ChannelInitializer<SocketChannel> {

    private CountDownLatch lathc;

    public SimpleChatClientInitializer(CountDownLatch lathc) {
        this.lathc = lathc;
    }

    private SimpleChatClientHandler handler;

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        handler =  new SimpleChatClientHandler(lathc);
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast(new IdleStateHandler(0, 0, 5));
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(81920, Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", handler);
    }

    public String getServerResult(){
        return handler.getResult();
    }
    //重置同步锁
    public void resetLathc(CountDownLatch initLathc) {
        handler.resetLatch(initLathc);
    }

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

客户端 SimpleChatClient

package com.netty.chart;

import java.util.concurrent.CountDownLatch;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.Delimiters;

public class SimpleChatClient {

    private final String host;
    private final int port;

    public SimpleChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            CountDownLatch lathc = new CountDownLatch(1);
            SimpleChatClientInitializer clientInitializer = new SimpleChatClientInitializer(lathc);
            Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
                    .handler(clientInitializer);
            ChannelFuture connect = bootstrap.connect(host, port);
            Channel channel = connect.sync().channel();
//          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                channel.write("bbbbbb啊啊啊" + "\r\n");
//              connect.awaitUninterruptibly();
//              Void void1 = connect.getNow();
//              System.out.println(void1.toString());
                channel.flush();
                lathc.await();//开启等待会等待服务器返回结果之后再执行下面的代码
                System.out.println("服务器返回 1:" + clientInitializer.getServerResult());

                Thread.sleep(30000);

                lathc = new CountDownLatch(1);//此处为控制同步的关键信息,注意此对象的流转
                clientInitializer.resetLathc(lathc);
                channel.write("bbbbbb啊啊啊1111" + "\r\n");
                channel.flush();
                lathc.await();
                System.out.println("服务器返回 2:" + clientInitializer.getServerResult());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//          group.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws Exception {
        new SimpleChatClient("127.0.0.1", 8888).run();
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty客户实现并发发送数据有多种方式,下面是其中两种常见的方式: 1. 使用线程池: - 创建一个线程池,例如`ExecutorService`。 - 在需要发送数据的地方,将发送逻辑封装成一个`Runnable`或`Callable`任务。 - 将任务提交给线程池执行,可以通过`execute()`方法提交`Runnable`任务,或者通过`submit()`方法提交`Callable`任务。 - 线程池会自动管理线程的创建和销毁,并发执行任务。 示例代码: ```java ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个大小为10的线程池 // 循环发送数据 for (int i = 0; i < 10; i++) { final int index = i; executorService.execute(() -> { // 发送数据的逻辑 // ... System.out.println("Task " + index + " executed"); }); } executorService.shutdown(); // 关闭线程池 ``` 2. 使用Netty的EventLoopGroup: - 创建一个`NioEventLoopGroup`,它管理了一组NIO线程,用于处理I/O操作。 - 在需要发送数据的地方,通过调用`ChannelHandlerContext`的`writeAndFlush()`方法发送数据。 - 由于EventLoopGroup内部已经实现了并发处理,因此可以同时处理多个请求。 示例代码: ```java EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { // 添加处理器 } }); // 连接到服务器 Channel channel = bootstrap.connect(host, port).sync().channel(); // 循环发送数据 for (int i = 0; i < 10; i++) { channel.writeAndFlush(Unpooled.copiedBuffer("data", CharsetUtil.UTF_8)); } // 等待关闭连接 channel.closeFuture().sync(); } finally { group.shutdownGracefully(); } ``` 这两种方式都可以实现Netty客户的并发发送数据,具体选择哪种方式取决于你的需求和场景。使用线程池可以更灵活地控制并发度,而使用EventLoopGroup则更符合Netty的设计思想。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值