初识Netty并用Netty搭建最基本的网络服务器和客户端

目录

目标

概述

实战

依赖

Netty服务端

Netty客户端


目标

初步了解Netty,用Netty搭建一个最基本的网络服务器和客户端。


概述

Netty官方的描述:

The Netty project is an effort to provide an asynchronous event-driven network application framework and tooling for the rapid development of maintainable high-performance and high-scalability protocol servers and clients.

In other words, Netty is an NIO client server framework that enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server development.

译文:

Netty是一个异步的、基于时间驱动的网络应用框架。用于快速开发可维护的高性能协议服务器和客户端。

换句话说,Netty是一个NIO客户端服务器框架,可以快速轻松地开发协议服务器和客户端等网络应用程序。它极大地简化和流线化了网络编程,例如TCP和UDP套接字服务器开发。


实战

依赖

		
		
			io.netty
			netty-all
			4.1.87.Final
		

Netty服务端

package com.ctx.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
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;

public class NettyServer {
    public static void main(String[] args) {
        //Netty服务端启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //一个EventLoop是一个单线程执行器。
        //一个EventLoop可以处理多个Channel的io操作,一旦EventLoop绑定了Channel就会一直由这个EventLoop负责Channel的io操作。
        serverBootstrap.group(new NioEventLoopGroup());
        //选择服务器的ServerSocketChannel实现,这里我选择NIO。
        serverBootstrap.channel(NioServerSocketChannel.class);
        //设置事件类型
        serverBootstrap.childHandler(new ChannelInitializer() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                //把ByteBuf解码为String
                nioSocketChannel.pipeline().addLast(new StringDecoder());
                //pipeline是流水线,Handler是工序,流水线可以有多个工序。
                //Handler分为入栈(Inbound)和出栈(Outbound)
                //自定义Handler
                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                    //处理读事件
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println(msg);
                    }
                });
            }
        });
        //设置服务器的监听端口
        serverBootstrap.bind(8999);
    }
}

Netty客户端

package com.ctx.bio;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class NettyClient{


    public static void main(String[] args) throws InterruptedException {
        //启动Netty客户端
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        //选择EventLoop
        bootstrap.group(eventExecutors);
        try {
            //选择客户端Channel实现,Channel是数据的传输通道。
            bootstrap.channel(NioSocketChannel.class);
            //添加处理器,
            bootstrap.handler(new ChannelInitializer() {
                //连接建立后初始化Channel
                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    //把字符串编码成ByteBuf
                    nioSocketChannel.pipeline().addLast(new StringEncoder());
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8999);
            channelFuture.sync();
            Channel channel = channelFuture.channel();
            //向服务器发送数据
            channel.writeAndFlush("Hello world!");
            channelFuture.channel().closeFuture().sync();
        } finally {
            System.out.println("连接关闭了。");
            eventExecutors.shutdownGracefully();
        }
    }
}

你可能感兴趣的:(Netty,Netty服务端和客户端,Netty服务器,Netty客户端)