Netty

Netty创建UCP#

客户端:

public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .handler(new MyChannelInitializer()); // 使用自定义初始化器
            Channel ch = b.bind(7398).sync().channel();
            ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("你好端口7397的bugstack虫洞栈,我是客户端小爱,你在吗!", Charset.forName("GBK")),
                new InetSocketAddress("127.0.0.1", 7397))).sync();
            ch.closeFuture().await();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}

服务端:

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BROADCAST, true) // 允许广播
             .handler(new ChannelInitializer<NioDatagramChannel>() {
                 @Override
                 protected void initChannel(NioDatagramChannel ch) {
                     ChannelPipeline pipeline = ch.pipeline();
                     pipeline.addLast(new MyServerHandler()); // 自定义处理器
                 }
             });
            ChannelFuture f = b.bind(7397).sync();
            System.out.println("itstack-demo-netty udp server start done.");
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

Netty创建TCP#

服务端:

package the.flash.myserve;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class TcpServer {
    private final int port;

    public TcpServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于接受连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于处理连接

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            // 添加解码器和编码器
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());
                            p.addLast(new TcpServerHandler());
                        }
                    });

            Channel serverChannel = b.bind("192.168.0.155", port).sync().channel();
            System.out.println("服务器启动在端口: " + port);
            serverChannel.closeFuture().await();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        TcpServer tcpServer = new TcpServer(8888);
        tcpServer.run();

    }
}

/**
 * 自定义业务处理
 */
class TcpServerHandler extends SimpleChannelInboundHandler<String> {

    // 使用线程安全的Map来存储客户端Channel引用
    private static final Map<Channel, String> clientMap = new ConcurrentHashMap<>();


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("收到来自" + msg);
        clientMap.put(ctx.channel(), "客户端" + clientMap.size());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 当通道就绪时,将其添加到映射中
        clientMap.put(ctx.channel(), "Client_" + clientMap.size());
        System.out.println("客户端 " + ctx.channel() + " 连接成功,分配ID: " + clientMap.get(ctx.channel()));

        // 安排定时任务发送消息
        ctx.channel().eventLoop().scheduleWithFixedDelay(() -> {
            // 确保使用正确的方法和参数发送消息
            TcpServerHandler.sendMessageToClient(ctx.channel(), "我是你die");
        }, 0, 3, TimeUnit.SECONDS); // 立即开始执行,之后每3秒执行一次
    }

    public static void sendMessageToClient(Channel channel, String message) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message + "\r\n");
        }
    }
}

客服端:

package the.flash.myclient;

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

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) // 使用NioSocketChannel作为客户端通道的实现
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     // 添加解码器和编码器
                     p.addLast(new StringDecoder());
                     p.addLast(new StringEncoder());
                     // 添加自定义的业务逻辑处理器
                     p.addLast(new SimpleChannelInboundHandler<String>() {
                         @Override
                         protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                             System.out.println("Client received: " + msg);
                         }
                     });
                 }
             });

            // 连接服务器
            Channel ch = b.connect(host, port).sync().channel();

            // 向服务器发送数据
            String content = "Hello, Netty Server";
            ch.writeAndFlush(content);

            // 等待服务器关闭连接
            ch.closeFuture().sync();
        } finally {
            // 优雅关闭线程组
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "192.168.0.155";
        int port = 8888;
        new NettyClient(host, port).run();
    }
}

作者:Esofar

出处:https://www.cnblogs.com/firsthelloworld/p/18383192

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   我不想学编丿程  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示