前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Netty入门(一)

Netty入门(一)

作者头像
tanoak
修改2018-06-27 15:59:56
5640
修改2018-06-27 15:59:56
举报
文章被收录于专栏:java闲聊java闲聊

在文章开始之前首先明确一个问题,为什么要使用Netty,Netty解决了什么问题,围绕着这个问题我们开始本篇文章的学习

  1. 为什么要使用Netty netty它是对jdk中nio模块的封装,你也可以不使用Netty,就像开发网站可以只使用Servlet+jsp一样。结果是效率低且Bug多
  2. Netty解决了什么问题 沿用知乎上的答案
代码语言:txt
复制
jdk强迫你必须用socket来写服务器,实际上是很繁琐的。缺乏一个高层次的api。
netty说,我来写jdk的socket,并给你一个新的更简洁的api,你傻瓜式的就能写好一个网络服务器(而且是event-driven/proactor/reactor等等)。
当然,netty通过jni,引入了epoll这样的linux系统调用,使得它不单单是jdk的一个简单包裹,的确也加了些东西进去

想深入了解Netty的应用场景和优势可以参考知乎上的问答知乎传送门

按照我的讲解风格,先运行代码,跑起来再问为什么

  1. 导入依赖 本项目使用的是Gradle,下载Jar包的速度慢,可以配置阿里云的仓库
代码语言:txt
复制
/*   repositories {
        maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
        mavenLocal()
        mavenCentral()
    }*/
 compile (group: 'io.netty', name: 'netty-all', version: '4.1.25.Final')
  1. 编写服务器端
代码语言:txt
复制
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

/**
 * @author tanoak@qq.com
 * @date 2018/6/26 22:46
 * @Desc
 */
public class NettyServer {
    // 端口号
    private final int port;
    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        ServerBootstrap serverBootstrap = new ServerBootstrap();//① 是一个启动NIO服务的辅助启动类
        NioEventLoopGroup worker = new NioEventLoopGroup();//②NioEventLoopGroup是用来处理IO操作的多线程事件循环器
        serverBootstrap
                .group(worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            //读取客户端发送的消息
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println("【客户端发送的消息】"+msg);
                            }
                        });
                    }
                })
                .bind(port);
    }

    public static void main(String[] args) throws Exception {
        try {
            new NettyServer( 8088).start();
            System.out.println("启动成功");
        }catch (Exception e){
            System.out.println("启动失败");
        }
    }
}
  1. 客户端
代码语言:txt
复制
import com.tanoak.demo1.client.EchoClientHandler;
import io.netty.bootstrap.Bootstrap;
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.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.Date;

/** 
 * @author tanoak@qq.com
 * @date 2018/6/25 0:46
 * @Desc
 */ 
public class NettyClient {
    private final String host;
    private final int port;
    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });
        Channel channel = bootstrap.connect(host, port).channel();
        while (true) {
            channel.writeAndFlush("现在时间:"+LocalDateTime.now());
            Thread.sleep(2000);
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyClient("127.0.0.1",8088 ).start();
    }
}

代码运行OK后我们接下来看下服务器端它所做的工作

  1. 创建ServerBootstrap对象以及 NioEventLoopGroup 对象 。然后进行优雅的链式调用,这里看一下group(worker)这个方法的源码

group()方法进行了重载,接着就是channel()方法添加一个NioServerSocketChannel的类,然后childHandler()上 目的是添加handler,用来监听已经连接的客户端的Channel的动作和状态,childHandler会在客户端成功connect后执行

接下来我们来看下客户端的工作

重复步骤省略直接看连接服务器的代码 bootstrap.connect(),接着就是利用channel 对象向服务器端写入数据

至此一个简单的Demo就完成了,如讲解有误,请指正,本篇参考《Netty实战》这本书,这本书个人极力推荐,想了解Netty的可以考虑入门一本

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.06.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档