(二)netty的hello world示例

一、简介

本章从Hello World 开始讲述Netty的中文教程。

工程目录如下:

 

 

二、实战

 

1.创建maven工程,添加如下依赖

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

 

 

2.服务端

Netty创建全部都是实现自AbstractBootstrap。客户端的是Bootstrap,服务端的则是ServerBootstrap。

①创建一个HelloServer

package com.example.nettytest01.helloserver;

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 HelloServer {
    //服务端监听的端口地址,自己选择,只要不占用到其它常用端口就可以
    private static final int portNumber = 7878;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boosGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            //Handler涉及很多领域。HTTP,UDP,Socket,WebSocket等等。
            b.childHandler(new HelloServerInitializer());

            //服务器绑定端口监听
            ChannelFuture f = b.bind(portNumber).sync();
            //监听服务器关闭监听,防止线程关闭
            f.channel().closeFuture().sync();
            /*可以简写为
            b.bind(portNumber).sync().channel().closeFuture().sync();*/
        }finally {
            /*顾名思义,优雅的全部关闭
            查看相应的源代码。我们可以在DefaultEventExecutorGroup的父类MultithreadEventExecutorGroup中看到它的实现代码。
            关闭了全部EventExecutor数组child里面子元素。
            相比于3.x版本这是一个比较重大的改动。
            开发者可以很轻松的全部关闭,而不需要担心出现内存泄露。*/
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

EventLoopGroup 是在4.x版本中提出来的一个新概念。用于channel的管理。服务端需要两个。和3.x版本一样,一个是boss线程一个是worker线程。

b.childHandler(new HelloServerInitializer()); //用于添加相关的Handler

服务端简单的代码,真的没有办法在精简了感觉。就是一个绑定端口操作。

 

②创建和实现HelloServerInitializer

在HelloServer中的HelloServerInitializer在这里实现。

首先我们需要明确我们到底是要做什么的。很简单。HelloWorld!。我们希望实现一个能够像服务端发送文字的功能。服务端假如可以最好还能返回点消息给客户端,让客户端去显示。

DelimiterBasedFrameDecoder Netty在官方网站上提供的示例显示 有这么一个解码器可以简单的消息分割(根据\n分割)。

其次 在decoder里面我们找到了String解码编码器。这都是官网提供给我们的。

package com.example.nettytest01.helloserver;

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 HelloServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        //以("\n")为结尾分割的 解码器
        pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

        //字符串解码和编码
        pipeline.addLast("decoder",new StringDecoder());
        pipeline.addLast("encoder",new StringEncoder());

        //自己的逻辑Handler
        pipeline.addLast("handler",new HelloServerHandler());
    }
}

上面的三个解码和编码都是框架自带的。

另外我们自己的Handler怎么办呢。在最后我们添加一个自己的Handler用于写自己的处理逻辑。

 

③增加自己的逻辑HelloServerHandler

自己的Handler我们这里先去继承extends官网推荐的SimpleChannelInboundHandler<C> 。在这里C,由于我们需求里面发送的是字符串。这里的C改写为String。

package com.example.nettytest01.helloserver;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;

public class HelloServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //收到消息直接打印输出
        System.out.println(ctx.channel().remoteAddress()+" Say:"+msg);
        //返回客户端消息 - 我已经接收到了你的消息。以二进制数据流的形势发送给客户端
        ctx.writeAndFlush("Received your message !\n");
    }

    /**
     * 覆盖channelActive方法在channel被启用的时候触发(在建立连接的时候)
     * channelActive和channelInActive在后面的内容中讲述,这里先不做详细的描述
     * @Param [ctx]
     * @return void
     **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("RemoteAddress:"+ctx.channel().remoteAddress()+"active!");
        ctx.writeAndFlush("Welcome to "+InetAddress.getLocalHost().getHostName()+" service!\n");
        super.channelActive(ctx);
    }
}

在ChannelHandlerContext自带一个writeAndFlush方法。方法的作用是写入Buffer并刷入。

注意:在3.x版本中此处有很大区别。在3.x版本中write()方法是自动flush的。在4.x版本的前面几个版本也是一样的。但是在4.0.9之后修改为WriteAndFlush。普通的write方法将不会发送消息。需要手动在write之后flush()一次

这里channelActive的意思是当连接活跃(建立)的时候触发.输出消息源的远程地址。并返回欢迎消息。

channelRead0 在这里的作用是类似于3.x版本的messageReceived()。可以当做是每一次收到消息是触发。

我们在这里的代码是返回客户端一个字符串"Received your message !".

注意:字符串最后面的"\n"是必须的。因为我们在前面的解码器DelimiterBasedFrameDecoder是一个根据字符串结尾为“\n”来结尾的。假如没有这个字符的话。解码会出现问题。

 

 

3.客户端

类似于服务端的代码。我们不做特别详细的解释。直接上示例代码:

①创建HelloClient

客户端仅仅只需要一个worker的EventLoopGroup。其次是类似于ServerBootstrap的HandlerInitializer。

package com.example.nettytest01.helloclient;

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;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HelloClient {
    public static String host = "127.0.0.1";
    public static int port = 7878;

    public static void main(String[] args) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new HelloClientInitializer());

            //连接服务端
            Channel channel = b.connect(host, port).sync().channel();

            //控制台输入
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for(;;){
                String line = in.readLine();
                if(line==null){
                    continue;
                }
                /*向服务端发送在控制台输入的文本,并用"\r\n"结尾,\r的作用是换行
                之所以用\n结尾,是因为我们在handler中添加了DelimiterBasedFrameDecoder 帧解码
                这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码*/
                channel.writeAndFlush(line+"\r\n");
            }
        }finally {
            // The connection is closed automatically on shutdown.
            group.shutdownGracefully();
        }
    }
}

 

②创建和实现HelloClientInitializer

package com.example.nettytest01.helloclient;

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 HelloClientInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

       /* 这个地方的必须和服务端对应上,否则无法正常解码和编码
        解码和编码 我将在下一章为大家详细的讲解。在此暂时不做详细的描述   */
        pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192,Delimiters.lineDelimiter()));
        pipeline.addLast("decoder",new StringDecoder());
        pipeline.addLast("encoder",new StringEncoder());

        //客户端的逻辑
        pipeline.addLast("handler",new HelloClientHandler());
    }
}

 

③创建HellClientHandler

package com.example.nettytest01.helloclient;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class HelloClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Server say: "+msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client active ");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client close ");
        super.channelInactive(ctx);
    }
}

 

 

三、测试

分别运行server和client。

在client端控制台输入消息按Enter键发送。

client控制台

server控制台

 

说明测试成功。

 

 

学习借鉴自https://www.cnblogs.com/zou90512/p/3492878.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值