使用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. phpcms ——模板标签详细使用说明

    使用phpcms总是要查询各种标签,实在很烦,只好找个比较全的来备查.因为自己写一个orm来配合调用也没那么容易无缝的嵌入到引擎当中. 获取父分类下面的子分类 {loop subcat(77) $k ...

  2. Zepto 添加手势判断拓展方法(思路+原理)

    一.前言 这几个月事情比较多,写了一些博客都没有来得及整理发布,今天刚好有一位同事在开发前端页面的时候用到了手势判断.所以翻出了之前写的 demo,顺便整理一下作为记录. 手势判断在各种应用中都十分常 ...

  3. Android -- 带你从源码角度领悟Dagger2入门到放弃(二)

    1,接着我们上一篇继续介绍,在上一篇我们介绍了简单的@Inject和@Component的结合使用,现在我们继续以老师和学生的例子,我们知道学生上课的时候都会有书籍来辅助听课,先来看看我们之前的Stu ...

  4. Linux-进程描述(4)之进程优先级与进程创建执行

    进程优先级 进程cpu资源分配就是指进程的优先权(priority).优先权高的进程有优先执行权利. 权限与优先级.权限(privilege)是指在多用户计算机系统的管理中,某个特定的用户具有特定的系 ...

  5. CSS3 制作网格动画效果

    在线演示      源码下载

  6. 【渗透测试】hydra使用小结

    -R:继续从上一次进度接着破解 -S:大写,采用SSL链接 -s <PORT>:小写,可通过这个参数指定非默认端口 -l <LOGIN>:指定破解的用户,对特定用户破解 -L ...

  7. Java中的集合与线程的Demo

    一.简单线程同步问题 package com.ietree.multithread.sync; import java.util.Vector; public class Tickets { publ ...

  8. jQuery修炼心得-DOM节点的插入

    1. 内部插入append()与appendTo() append:这个操作与对指定的元素执行原生的appendChild方法,将它们添加到文档中的情况类似. appendTo:实际上,使用这个方法是 ...

  9. 点击滚动图片JS部分代码以及css设置注意事项

    下面js代码可以实现8张图片点击左右按钮后切换的过渡动画效果 var pslul11=document.getElementById('pslul11')var pslspan1=document.g ...

  10. Linux常用快捷按键

    Linux常用快捷按键 为了提高工作效率 1 一定用快捷键 这里简单的说下几个常用的快捷按键. Ctrl + l    清屏,相当于clear命令. Ctrl + z    挂起,程序放到后台,程序没 ...