使用maven构建一个基本的netty收发应用,作为其他应用的基础。客户端使用packet sender工具。

1  添加netty依赖

1  maven netty依赖

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

2  添加ServerBootstrap启动函数

package io.netty.example.basic;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
* main class
* @author Sylar
* @Time 2017-01-02
*/
public class NettyBaisc {

private int port;
    public NettyBaisc(int port) {
        this.port = port;
    }

public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
           
            /*创建一个新的 ServerBootstrap 来创建和绑定新的 Channel
            指定 EventLoopGroups 从 ServerChannel 和接收到的管道来注册并获取 EventLoops
            指定 Channel 类来使用
            设置处理器用于处理接收到的管道的 I/O 和数据
            通过配置的引导来绑定管道
            ChannelInitializer 负责设置 ChannelPipeline
            实现 initChannel() 来添加需要的处理器到 ChannelPipeline。一旦完成了这方法 ChannelInitializer 将会从 ChannelPipeline 删除自身。*/
           
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new NettyBaiscHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

// Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)

// Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new NettyBaisc(port).run();
    }
}

3  添加通道handler

package io.netty.example.basic;

import java.io.UnsupportedEncodingException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
/**
* handler class
* @author Sylar
* @Time 2017-01-02
*/
public class NettyBaiscHandler extends ChannelInboundHandlerAdapter { // (1)
     @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(">>>>>>>>connect in>>>>>>>>");
        }
     @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(">>>>>>>>connect out>>>>>>>>");
        }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
       
        /*byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req);       
        System.out.println("Server received: " + body);*/
       
        System.out.println("Client received: " + buf.toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(Unpooled.copiedBuffer("Ack", CharsetUtil.UTF_8));
        /*ctx.write(Unpooled.copiedBuffer("Ack", CharsetUtil.UTF_8));
        ctx.flush();*/
    }
   /* public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        // Discard the received data silently.
        //((ByteBuf) msg).release(); // (3)
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                System.out.print((char) in.readByte());
                System.out.flush();
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
    }*/

@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}

4  参考

  • netty官网的echo示例

http://netty.io/wiki/user-guide-for-4.x.html

  • channel不能发送string的问题说明

(我在去年底的测试中是可以直接发送字符串的,有些奇怪!)

http://stackoverflow.com/questions/25760764/netty-channel-write-not-writing-message

netty基础--基本收发的更多相关文章

  1. Netty基础系列(3) --彻底理解NIO

    前言 上一节中我们提到了同步异步与阻塞非阻塞的区别,知道了同步并不等于阻塞.而本节的主角NIO是一种同步非阻塞的I/O模型,并且是I/O多路复用模型.NIO在java中被称为 New I/O.它并不能 ...

  2. Netty基础系列(4) --堆外内存与零拷贝详解

    前言 到目前为止,我们知道Nio当中有三个最最核心的组件,分别是:Selelctor,Channel,Buffer.在Netty基础系列(3) --彻底理解NIO 这一篇文章中只是进行了大致的介绍. ...

  3. Netty基础系列(1) --linux网路I/O模型

    引言 我一直认为对于java的学习,掌握基础的性价比要远远高于使用框架,而基础知识中对于网络相关知识的掌握也是重中之重.对于一个java程序来说,无论是工作中还是面试,对于Netty的掌握都是及其重要 ...

  4. Netty基础点滴

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

  5. Netty基础系列(2) --彻底理解阻塞非阻塞与同步异步的区别

    引言 在进行I/O学习的时候,阻塞和非阻塞,同步和异步这几个概念常常被提及,但是很多人对这几个概念一直很模糊.要想学好Netty,这几个概念必须要掌握清楚. 同步和异步 同步与异步的区别在于,异步基于 ...

  6. 2、Netty基础

    一.前言 主要包含下面内容: 初识 Netty: 使用 Java NIO 搭建简单的客户端与服务端实现网络通讯: 使用 Netty 搭建简单的客户端与服务端实现网络通讯: Netty 底层操作与 Ja ...

  7. netty 基础

    Netty是一个高性能.异步事件驱动的NIO框架,提供了对TCP.UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过Future-Listener机制,用户 ...

  8. Python微信公众号教程基础篇——收发文本消息

    1. 概述: 在本篇教程中,你将学会使用华为云弹性云服务器(以下简称 ECS)搭建微信公众号处理后台,使用Python语言编写对应的微信消息处理逻辑代码,接收从微信服务端转发过来的消息,并返回处理结果 ...

  9. Netty基础-BIO/NIO/AIO

    同步阻塞IO(BIO): 我们熟知的Socket编程就是BIO,每个请求对应一个线程去处理.一个socket连接一个处理线程(这个线程负责这个Socket连接的一系列数据传输操作).阻塞的原因在于:操 ...

随机推荐

  1. Java中ArrayList,Vector,LinkedList,HashMap,HashTable,HashSet对比及总结

    1.所有的集合的父类都是Collection的接口 2.Set List Map 区别 A  在Set里面:无法添加元素的顺序,所以Set里面的元素不能重复 B  在List中:有索引号,类似于数组, ...

  2. 严格模式下的javascript

    arguments: ECMA5移除了实参对象(arguments),在非严格模式下函数里的arguments只是一个标识符,在严格模式下它变成了保留字.严格模式下无法使用arguments作为形参名 ...

  3. iOS实现高斯模糊效果(Swift版本)

    给UIimage添加分类 extension UIImage { /// 高斯模糊 func gaussianBlur(var blurAmount:CGFloat) -> UIImage { ...

  4. sql中的复制函数REPLICATE

    REPLICATE函数: REPLICATE(字符串,次数)复制一个字符串n次 ) --输出结果:0000000000

  5. GitHub上最受欢迎的iOS开源项目TOP20

    AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是GitH ...

  6. 今天开始上Linux运维课。

    2017年4月25日,北京.沙河老男孩教育,Linux运维. 我是其中一员,希望顺利!

  7. 远程SSH连接服务与基本排错

    为什么要远程连接Linux系统?? 在实际的工作场景中,虚拟机界面或物理服务器本地的窗口都是很少能够接触到的,因为服务器装完系统后,都要拉到IDC机房托管,如果是购买了云主机,更碰不到服务器本地显示器 ...

  8. final的用法

    先来看一段代码 class Car extends Vehicle {     public static void main (String[] args)     {         new  C ...

  9. jquery获取文件名称

    $("#fileupload").on("change",function(){ var filePath=$(this).val(); if(filePath ...

  10. Android WebView导入HTML使Js生效的方法

    WebSettings ws = webview.getSettings(); ws.setJavaScriptEnabled(true);//加上这句 webview.loadDataWithBas ...