网络编程--(三)Netty入门

本文介绍如何使用Netty框架快速开发网络应用,包括服务器和客户端的搭建过程。Netty简化了网络编程复杂性,使得开发者能够专注于业务逻辑而非底层通信细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在我们学习一门新的技术,我们为什么选择Netty,原因无他,简单! 我们再也不必去编写复杂的代码逻辑去实现通信,我们再也不需要去考虑性能的问题,不需要考虑编码问题,半包读写问题等等,Netty已经帮我们实现好了,我们只需要使用即可。

Netty也是最流行的NIO框架.

Netty是一个NIO client-server(客户端服务器)框架,使用Netty可以快速开发网络应用,例如服务器和客户端协议。Netty提供了一种新的方式来使开发网络应用程序,

Netty是完全基于NIO实现的,所以整个Netty都是异步的。

 

Netty实现通信的步骤

1.创建两个的NIO线程组,一个专门用于网络事件处理 (接受客户端的链接),另一个则进行网络通信读写。

2.创建一个ServerBootstrap对象,配置Netty的一系列参数,例如接受传出数据的缓存大小等。

3.创建一个实际处理数据的类Channellnitialzer,进行初始化的准备工作,比如设置接受传出数据的字符集、格式、已经实际处理数据的接口。

4.绑定端口、执行同步阻塞方法等待服务器端启动即可

复制代码
package bhz.netty.test;

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;

public class Server {

    public static void main(String[] args) throws Exception {
        //1 第一个线程组 是用于接收Client端连接的
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2 第二个线程组 是用于实际的业务处理操作的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        //3 创建一个辅助类Bootstrap,就是对我们的Server进行一系列的配置
        ServerBootstrap b = new ServerBootstrap(); 
        //把俩个工作线程组加入进来
        b.group(bossGroup, workerGroup)
        //我要指定使用NioServerSocketChannel这种类型的通道
         .channel(NioServerSocketChannel.class)
        //一定要使用 childHandler 去绑定具体的 事件处理器
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ServerHandler());
            }
        });

        //绑定指定的端口 进行监听
        ChannelFuture f = b.bind(8765).sync(); 
        
        //Thread.sleep(1000000);
        f.channel().closeFuture().sync();
        
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
         
        
        
    }
    
}
复制代码
复制代码
package bhz.netty.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 Client {

    public static void main(String[] args) throws Exception {
        
        EventLoopGroup workgroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(workgroup)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ClientHandler());
            }
        });
        
        ChannelFuture cf1 = b.connect("127.0.0.1", 8765).sync();
        
        //写入
        cf1.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));
        
        cf1.channel().closeFuture().sync();
        workgroup.shutdownGracefully();
        
    }
}
复制代码
复制代码
package bhz.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            //do something msg
            ByteBuf buf = (ByteBuf)msg;
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            String request = new String(data, "utf-8");
            System.out.println("Client: " + request);
            
            
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
复制代码
复制代码
package bhz.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ServerHandler  extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    
            //do something msg
            ByteBuf buf = (ByteBuf)msg; 
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            String request = new String(data, "utf-8");
            System.out.println("Server: " + request);
            //写给客户端
            String response = "我是反馈的信息";
            ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()))
            .addListener(ChannelFutureListener.CLOSE);   //当服务器端写完客户端收到后断开客户端连接
            

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
复制代码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值