第一个netty demo

环境

  • maven
  • JDK7
  • netty4.1.11.Final

netty工作原理

这里写图片描述
1. 客户端连接到服务器
2. 建立连接后,发送或接收数据
3. 服务器处理所有的客户端连接

netty demo

写一个Netty服务器主要由两部分组成:
- 配置服务器功能,如线程、端口
- 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么

maven依赖

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

server端

服务端启动类EchoServer

package com.beidao.netty.demo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {

    private int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(group);
            bootstrap.channel(NioServerSocketChannel.class);
            //设置过滤器
            bootstrap.childHandler(new EchoServerFilter()); 
            // 服务器绑定端口监听
            ChannelFuture f = bootstrap.bind(port).sync();
            System.out.println(EchoServer.class.getName() + "started and listen on" + f.channel().localAddress());
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new EchoServer(5555).start();

    }

}

服务端数据过滤器EchoServerFilter

package com.beidao.netty.demo.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class EchoServerFilter extends ChannelInitializer<SocketChannel>{

     @Override
     protected void initChannel(SocketChannel ch) throws Exception {
         ChannelPipeline ph = ch.pipeline();
         // 以("\n")为结尾分割的 解码器
         ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
         // 解码和编码,应和客户端一致
         ph.addLast("decoder", new StringDecoder());
         ph.addLast("encoder", new StringEncoder());
         ph.addLast("handler", new EchoServerHandler());// 服务端业务逻辑
     }
}

服务端连接拦截器EchoServerHandler

package com.beidao.netty.demo.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter{

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        System.out.println("Server received: " + msg);
        ctx.write(msg);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

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

client端

客户端启动类EchoClient

package com.beidao.netty.demo.client;

import java.io.IOException;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class EchoClient {

    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.port = port;
        this.host = host;
    }

    public void start() throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new EchoClientFilter());
        // 连接服务端
        Channel ch = bootstrap.connect(host, port).sync().channel();
        sendData(ch);
    }

    public static void sendData(Channel ch) throws IOException{
        String str="Hello Netty";
        ch.writeAndFlush(str+ "\r\n");
        System.out.println("sending data:"+str);
   }

    public static void main(String[] args) throws InterruptedException, IOException {
        new EchoClient("localhost", 5555).start();
    }

}

客户端数据传输过滤器EchoClientFilter

package com.beidao.netty.demo.client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class EchoClientFilter extends ChannelInitializer<SocketChannel>{

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline ph = ch.pipeline();
            /*
             * 解码和编码,应和服务端一致
             * */
            ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
            ph.addLast("decoder", new StringDecoder());
            ph.addLast("encoder", new StringEncoder());
            ph.addLast("handler", new EchoClientHandler()); //客户端的逻辑
    }

}

客户端连接拦截器EchoClientHandler

package com.beidao.netty.demo.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("connecting... ");
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("Client received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes())));
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
         System.out.println("connect closed! ");
         super.channelInactive(ctx);
    }
}

验证

运行EchoServer启动server端,控制台信息如下:

com.beidao.netty.demo.server.EchoServerstarted and listen on/0:0:0:0:0:0:0:0:5555

运行EchoClient启动client端,控制台信息如下:

connecting... 
sending data:Hello Netty

此时,server端客户端控制台信息如下:

Server received: Hello Netty

源码地址:https://github.com/MAXAmbitious/netty-study

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值