netty学习(一),搭建netty服务端

使用netty搭建服务端:

netty服务至少要有两个部分:

1.ChannelHandler-该组建实现了服务器对从客户端接受数据的处理,即业务逻辑

2.引导-配置服务器启动。

ChannelHandler仅仅是一个接口,继承他的有ChannelInboundHandler和ChannelOutboundHandler,分别是进站和出站事件的响应。

由于服务器接收消息是进站事件,我们暂时只实现一个简单的进站Handler。

先来编写一个入站的事件相应:

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class FirstHandler extends SimpleChannelInboundHandler<String> {

    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        ByteBuf buf = Unpooled.buffer();
        System.out.println("receive message " + s);
        ctx.writeAndFlush(buf.writeBytes("first reply".getBytes()));
    }
   @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.buffer();
        ctx.writeAndFlush(buf.writeBytes("this is server".getBytes()));
    }

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

入站的Handler我们继承了SimpleChannelInboundHandler,它继承于ChannelInboundHandlerAdapter,在消息入站的实现上,自动为我们做了内存的释放。

对上面代码进行一个简单的说明,channelRead0是当有入站消息的时候对触发的方法,并且触发后,调ChannelHandlerContext的fireChannelRead的方法,会沿着当前的Handler向出站的方向流动,在netty服务器配置引导的时候,会在管道上绑Handler,并且加入ChannelHandlerContext,ChannelHandlerContext和Handler一一对应。当调用ctx.writeAndFlush时,它会沿着当前方向寻找同样是出站方向的Handler,然后进行处理。

配置引导,启动服务:

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

import java.util.concurrent.TimeUnit;

public class AbsTcpServer {

    public void start() {
        ServerBootstrap b = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();

        b.group(group, work)
                .channel(NioServerSocketChannel.class)
                .childHandler(getChannel());

        try {
            ChannelFuture f = b.bind(8080).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

    public ChannelInitializer<SocketChannel> getChannel() {
        return new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new FirstHandler())
                ;

            }
        };
    }



    public static void main(String[] args) {
        AbsTcpServer absTcpServer = new AbsTcpServer();
        absTcpServer.start();
    }

}

这样一个基于netty的服务端就完成了。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值