美文网首页
Netty入门(一)

Netty入门(一)

作者: tanoak | 来源:发表于2018-06-27 00:47 被阅读51次

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

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

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

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

  1. 导入依赖
    本项目使用的是Gradle,下载Jar包的速度慢,可以配置阿里云的仓库
/*   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. 编写服务器端
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. 客户端


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的可以考虑入门一本

相关文章

  • Netty 实现简单的通讯

    一、netty入门 一,Netty是什么 1,Netty是由JBOSS提供的一个java开源框架。 2,Netty...

  • netty服务端和客户端

    netty简单入门:netty版本大致版本分为 netty3.x 和 netty4.x、netty5.x n...

  • netty通信框架

    Netty入门教程——认识Netty彻底理解Netty,这一篇文章就够了 Netty特点 并发高 传输快 封装好 ...

  • netty 线程模型(未完成)

    参考 Netty原理架构解析 netty 入门 netty工作原理架构图+ 虽然Netty的线程模型基于主从Rea...

  • Netty 入门

    title: Netty 入门date: 2021/04/06 09:37 一、Netty 概述 1.1 Nett...

  • Netty入门实践

    Netty基础概念 欢迎访问微信原文:Netty入门实践 Bootstrap 和 ServerBootstrap:...

  • Netty高速网络通讯(一)

    1、Netty基础入门 Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应...

  • Netty之ByteBuf

    通过Netty之Helloworld一文,我们简单的对Netty进行了入门,本文说一下Netty的数据容器Byte...

  • 1.Netty入门

    Netty入门 1.Netty介绍 (1)百度百科介绍: Netty是由JBOSS提供的一个java开源框架。Ne...

  • 高性能NIO框架Netty-对象传输

    上篇文章高性能NIO框架Netty入门篇我们对Netty做了一个简单的介绍,并且写了一个入门的Demo,客户端往服...

网友评论

      本文标题:Netty入门(一)

      本文链接:https://www.haomeiwen.com/subject/sbheyftx.html