Netty(八) 多客户端连接例子

Netty(八) 多客户端连接例子

netty学习目录
一、Netty(一) NIO例子
二、Netty(二) netty服务端
三、Netty(三) Netty客户端+服务端
四、Netty(四) 简化版Netty源码
五、Netty(五)Netty5.x服务端
六、Netty(六) Netty Http 服务器例子
七、Netty(七) Netty服务端+客户端代码
八、Netty(八) Netty多客户端连接例子
九、Netty(九) Netty会话清除
十、Netty(十) Netty自定义编码器解码器
十一、Netty(十一) Netty对象传输

多客户端连接,支持重连

package com.zqw.netty5x;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class MutiClient1 {
    private Bootstrap bootstrap = new Bootstrap();
    private final AtomicInteger index = new AtomicInteger();
    //会话对象组
    private List<Channel> channels = new ArrayList<>();
    public void init(int count){
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new ClientHandler1());
            }
        });
        for(int i=0; i<count;i++){
            Channel channel = bootstrap
                    .connect(new InetSocketAddress("192.168.1.4", 7777)).channel();
            channels.add(channel);
        }

    }
    public Channel next(){
        //获取可用的channel
        return getChannel(0);
    }
    private Channel getChannel(int count){
        Channel channel = channels.get(Math.abs(this.index.getAndIncrement()%channels.size()));
        if(count >= channels.size()){
            throw new RuntimeException("没有足够的channel");
        }
        if(!channel.isActive()){
            //重连
            reconnect(channel);
            //尝试获取下一个channel
            return getChannel(++count);
        }
        return channel;
    }

    private void reconnect(Channel channel) {
        synchronized (channel){
            int index = channels.indexOf(channel);
            channel =  bootstrap
                    .connect(new InetSocketAddress("192.168.1.4", 7777)).channel();
            channels.set(index, channel);
        }
    }

    public static void main(String[] args) {
        MutiClient1 mutiClient = new MutiClient1();
        mutiClient.init(10);
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入:");
            String str = scanner.next();
            try {
                Channel channel = mutiClient.next();
                channel.writeAndFlush(str);
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }

}
package com.zqw.netty5x;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandlerInvoker;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;

public class ClientHandler1 extends SimpleChannelInboundHandler<String> {
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }
}
以下是一个 Netty Socket 服务器示例,可以主动向10000个客户端分发消息: ```java import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; public class NettyClient { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; } public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) throws Exception { String host = "localhost"; int port = 8080; NettyClient client = new NettyClient(host, port); client.run(); } } import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send message to server String message = "Hello, server!"; ByteBuf buf = Unpooled.copiedBuffer(message, CharsetUtil.UTF_8); ctx.writeAndFlush(buf); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; String received = in.toString(CharsetUtil.UTF_8); System.out.println("Client received: " + received); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 在上面的示例中,我们创建了一个 `Bootstrap`,并将其连接到指定的主机和端口。当客户端与服务器连接时,`NettyClientHandler` 类将被调用来处理服务器的响应。 下面是 `NettyClientHandler` 的示例代码,它将接收到的消息打印到控制台上: ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class NettyClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send message to server String message = "Hello, server!"; ByteBuf buf = Unpooled.copiedBuffer(message, CharsetUtil.UTF_8); ctx.writeAndFlush(buf); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; String received = in.toString(CharsetUtil.UTF_8); System.out.println("Client received: " + received); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 在上面的示例中,当客户端接收到服务器的消息时,它将使用 `System.out.println()` 方法将消息打印到控制台上。 使用上述示例代码可以很容易地实现一个 Netty Socket 服务器,可以主动向10000个客户端分发消息。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值