netty基础--基本收发
使用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基础--基本收发的更多相关文章
- Netty基础系列(3) --彻底理解NIO
前言 上一节中我们提到了同步异步与阻塞非阻塞的区别,知道了同步并不等于阻塞.而本节的主角NIO是一种同步非阻塞的I/O模型,并且是I/O多路复用模型.NIO在java中被称为 New I/O.它并不能 ...
- Netty基础系列(4) --堆外内存与零拷贝详解
前言 到目前为止,我们知道Nio当中有三个最最核心的组件,分别是:Selelctor,Channel,Buffer.在Netty基础系列(3) --彻底理解NIO 这一篇文章中只是进行了大致的介绍. ...
- Netty基础系列(1) --linux网路I/O模型
引言 我一直认为对于java的学习,掌握基础的性价比要远远高于使用框架,而基础知识中对于网络相关知识的掌握也是重中之重.对于一个java程序来说,无论是工作中还是面试,对于Netty的掌握都是及其重要 ...
- Netty基础点滴
编写一个应答服务器 编写一个应答服务器 写一个Netty服务器主要由两部分组成: 配置服务器功能,如线程.端口 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么 启动服务器 ...
- Netty基础系列(2) --彻底理解阻塞非阻塞与同步异步的区别
引言 在进行I/O学习的时候,阻塞和非阻塞,同步和异步这几个概念常常被提及,但是很多人对这几个概念一直很模糊.要想学好Netty,这几个概念必须要掌握清楚. 同步和异步 同步与异步的区别在于,异步基于 ...
- 2、Netty基础
一.前言 主要包含下面内容: 初识 Netty: 使用 Java NIO 搭建简单的客户端与服务端实现网络通讯: 使用 Netty 搭建简单的客户端与服务端实现网络通讯: Netty 底层操作与 Ja ...
- netty 基础
Netty是一个高性能.异步事件驱动的NIO框架,提供了对TCP.UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过Future-Listener机制,用户 ...
- Python微信公众号教程基础篇——收发文本消息
1. 概述: 在本篇教程中,你将学会使用华为云弹性云服务器(以下简称 ECS)搭建微信公众号处理后台,使用Python语言编写对应的微信消息处理逻辑代码,接收从微信服务端转发过来的消息,并返回处理结果 ...
- Netty基础-BIO/NIO/AIO
同步阻塞IO(BIO): 我们熟知的Socket编程就是BIO,每个请求对应一个线程去处理.一个socket连接一个处理线程(这个线程负责这个Socket连接的一系列数据传输操作).阻塞的原因在于:操 ...
随机推荐
- ios 获取当前设备信息、内存
//在[UIDevice currentDevice]中的属性 @property(nonatomic,readonly,strong) NSString *name; // e.g. "M ...
- js原型对象
原型对象是什么? 在js中,每一个创建的的函数都会有一个prototype属性,这个属性指向一个对象,这个对象就是原型对象 function lla(){} console.log(lla.proto ...
- MongoDB系列:把mongodb作为windows的服务来启动
1.首先切换到mongodb安装目录下的bin目录,在控制台直接运行以下命令 "C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe" ...
- Elasticsearch搜索之most_fields分析
顾名思义,most_field就是匹配词干的字段数越多,分数越高,也可设置权重boost. 下面是简易公式(详细评分算法请参考:http://m.blog.csdn.net/article/detai ...
- TomCat杀进程
有时候当你的tomcat启动时会发现 因为报以下的错误: "Several ports ( 8080, 8009) required by Tomcat v6.0 Server at loc ...
- ECharts 实现人民的名义关系图谱 代码开源
1.什么是ECharts ECharts是百度开源的纯 Javascript 图表库,目前开源可以与highcharts相匹敌的一个图表库,相信有很多国内用户使用. 官网 http://echarts ...
- NI Vision for LabVIEW 基础(一):NI Vision 简介
NI Vision 控件模板 Vision控件模板位于LabVIEW控件模板的最顶层,由一下元素组成: IMAQ Image.ctl—该控件是一个类型定义,用于声明图象类型的数据.在VI的前面板中使用 ...
- websoket使用Protocol Buffers3.0传输
Protocol Buffers是Google推出的一个数据交换格式,相对于xml它的体积更小,更快,因为它是二进制传输的.3.0相对于2.0变动比较大.这些变动可以去看官方说明. 在前端使用Prot ...
- 使用wcf编写坐标字符串生成shapefile文件,在iis发布供前端调用
项目有一需求,需要由坐标字符串(格式:x,y,点名)生成shapefile,由于在前台开发类似功能比较麻烦而且也不适用,最终决定使用WCF来实现,不借助现有GIS软件,基于GDAL实现. 实现过程如下 ...
- 利用GDB进行多线程调试
一.多线程调试 多线程调试重要就是下面几个命令: info thread 查看当前进程的线程. thread <ID> 切换调试的线程为指定ID的线程. break file.c:100 ...