Netty(1) hello World

服务端

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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 io.netty.handler.codec.string.StringEncoder;

public class Server {
    public static void main(String[] args) {

  
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            // 创建服务端
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 设置线程组
            serverBootstrap.group(bossGroup, workGroup)
                    // 设置为nio模式
                    .channel(NioServerSocketChannel.class)
                    // 设置keepAlive 为true 监控客户端连接是否有效无效就断开连接
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    // 设定通道初始值
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 为管道设置编解码器 
                            ChannelPipeline channelPipeline = ch.pipeline();
                            channelPipeline.addLast(new StringDecoder());
                            channelPipeline.addLast(new StringEncoder());
                            // 自定义的Handler处理来自客户端的请求
                            channelPipeline.addLast(new MyServerHandler());
                        }
                    });
            // 让主线程阻塞 
            ChannelFuture future = serverBootstrap.bind(8790).sync(); // (7)
            // 关闭服务端
            future.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            // 关闭线程组
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }


    }
}

服务端Handler

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class MyServerHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("收到客户端:"+msg);
        // 写入到管道
        ctx.write(" hi 客户端");
        // 刷新管道(发送)
        ctx.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // 有异常的时候关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}

客户端

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {

        // 创建线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap(); // 创建客户端Bootstrap
            bootstrap.group(workerGroup); // 设置线程组 客户端只需要单个线程组
            bootstrap.channel(NioSocketChannel.class); // 设置为客户端nio
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 添加编解码器
                    ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new StringDecoder());
                    // 自定义消息处理
                    ch.pipeline().addLast(new MyClientHandler());
                }
            });

            // 设置服务端的ip和端口
            ChannelFuture connect = bootstrap.connect("127.0.0.1", 8790).sync();
            Channel channel = connect.channel();
            Scanner scanner = new Scanner(System.in);
            for (int i = 0; i < 5; i++) {
                Thread.sleep(500);
                System.out.println("请输入发送的消息:");
                channel.writeAndFlush(scanner.next());
            }
            channel.closeFuture().sync();
            // 关闭连接
            channel.closeFuture();
        } finally {
            // 关闭线程组
            workerGroup.shutdownGracefully();
        }
    }
}

客户端Handler

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class MyClientHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("收到服务端:"+msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值