第一个Netty实例

Netty实例

实现一个Echo的例子,使用Socket和Netty来实现,并且类比其中的相似性。
netty1.jpg

Socket实现方式

Server.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    private ServerSocket serverSocket;

    public Server(int port){
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务端启动, 端口:" + port);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务端启动失败");
        }
    }

    public void start(){
        new Thread(()->{
            doWork();
        }).start();
    }
    private void doWork(){
        while (true){
            try {
                Socket socket = serverSocket.accept();
                new WorkHandler(socket).start();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("服务端异常");
            }

        }
    }

    public static void main(String[] args) {
        Server server = new Server(8080);
        server.start();
    }
}

WorkHandler.java

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class WorkHandler {

    private Socket socket;

    private static final int MAX_LENGTH = 1024;

    public WorkHandler(Socket socket){
        this.socket = socket;
    }

    public void start(){
        System.out.println("新客户端接入");
        new Thread(()->{
            work();
        }).start();
    }
    private void work(){
        try {
            InputStream inputStream = socket.getInputStream();
            while (true){
                byte[] data = new byte[MAX_LENGTH];
                int len;
                while((len = inputStream.read(data)) != -1){
                    String message = new String(data, 0, len);
                    System.out.println("from client : " + message);
                    socket.getOutputStream().write(data); // 输出到客户端
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Netty 实现方式

使用maven添加Netty依赖

<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.5.Final</version>
</dependency>

EchoServer.java

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

public class EchoServer {

    public static void main(String[] args) {
        EventLoopGroup masterGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap server = new ServerBootstrap();
        server.group(masterGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new Serverhandler()) // 接受客户端连接信息
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                         // 业务逻辑
                        System.out.println("business logic");
                    }
                });
        try {
            ChannelFuture future = server.bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            masterGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}

ServerHandler.java

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class Serverhandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("channelActive");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        System.out.println("channelRegistered");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("handlerAdded");
    }
}

简单的类比

  • Socket类比Netty 的Channel
  • while循环类比NioEventLoop#run
  • 接受和业务逻辑在ChannelHandler中
添加新评论