Netty-简单示例

归档

JDK-示例

  • ref: https://github.com/zengxf/small-frame-demo/tree/master/jdk-demo/simple-demo/src/main/java/test/socket/nio

Netty-示例

  • codec 模块下创建用例
    • 包名:mytest

服务端

package io.netty.handler.codec.mytest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

public class MyServerTest {
    static int PORT = 8899;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup elg = new NioEventLoopGroup(2);
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(elg);
        sb.channel(NioServerSocketChannel.class);       // 设置 NIO 类型的 Channel
        sb.localAddress(new InetSocketAddress(PORT));   // 设置监听端口

        // 装配流水线
        sb.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel sc) { // 有连接到达时就会创建 Channel
                sc.pipeline().addLast("toStr", new StringDecoder());    // 接收时用解码器
                sc.pipeline().addLast("test", new TestHandler());       // sign_demo_010
            }
        });
        ChannelFuture cf = sb.bind().sync(); // sign_demo_001
        System.out.println("启动完成 -------------");
        cf.channel().closeFuture().sync();
        System.out.println("关闭完成 -------------");
        elg.shutdownGracefully();
    }

    static class TestHandler extends ChannelInboundHandlerAdapter {
        @Override // sign_demo_020
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            new RuntimeException("栈跟踪-处理器被添加").printStackTrace();
            super.handlerAdded(ctx);
        }

        @Override // sign_demo_021
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            new RuntimeException("栈跟踪-处理器被注册").printStackTrace();
            super.channelRegistered(ctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("读取消息:" + msg);
            super.channelRead(ctx, msg);
        }
    }
}

客户端

package io.netty.handler.codec.mytest;

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.StringEncoder;

import java.time.LocalTime;

public class MyClientTest {
    public static void main(String[] args) {
        EventLoopGroup elg = new NioEventLoopGroup(1);
        Bootstrap cb = new Bootstrap();
        cb.group(elg);
        cb.channel(NioSocketChannel.class);
        cb.remoteAddress("localhost", MyServerTest.PORT);

        // 设置通道初始化
        cb.handler(new ChannelInitializer<SocketChannel>() {
            public void initChannel(SocketChannel ch) {
                ch.pipeline().addLast("toByte", new StringEncoder()); // 发送时用编码器
            }
        });
        System.out.println("客户端开始连接...");
        ChannelFuture cf = cb.connect(); // 异步发起连接

        cf.addListener((ChannelFuture f) -> {
            if (f.isSuccess()) {
                System.out.println("连接成功!");
                String msg = "中-Test 123..." + LocalTime.now();
                Channel channel = f.channel();
                channel.write(msg); // sign_u_001 写入消息
                System.out.println("发送消息:" + msg);
                channel.flush();    // sign_u_002 推送消息
                channel.close().sync();     // 关闭 channel
                elg.shutdownGracefully();   // 关闭线程池(这样才会退出)
            } else {
                System.out.println("连接还未成功!");
            }
        });
    }
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值