Netty入门实例及分析
an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance and high scalability protocol servers and clients. In other words, Netty is
a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP/IP
socket server.
有一个boss thread。它主要是有请求要发出时试图进行一次连接。连接成功后,将这个连接的通道交付给一个worker thread。接下来这个worker thread 为一个或多个通道运行非堵塞的读写服务。
handlers) {
i ++) {
thread去处理。
import java.net.InetSocketAddress;
import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; public class TimeClient {
public static void main(String[] args) {
String host = args[0];
int port = Integer.parseInt(args[1]); ChannelFactory factory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
ClientBootstrap bootstrap = new ClientBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new TimeClientHandler2());
}
});
bootstrap.connect(new InetSocketAddress(host, port)); //
} }
import java.util.Date; import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler; public class TimeClientHandler extends SimpleChannelHandler{
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
ChannelBuffer buffer = (ChannelBuffer)e.getMessage();
long currentTimeMills = buffer.readInt() * 1000L;
System.out.println(new Date(currentTimeMills));
e.getChannel().close();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
e.getCause().printStackTrace();
Channel c = e.getChannel();
c.close();
}
}
import java.net.InetSocketAddress;
import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; public class TimeServer {
public static ChannelGroup allChannels = new DefaultChannelGroup("time-server"); public static void main(String[] args) {
ChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new TimeServerHandler2(),
new TimeEncoder());
}
}); bootstrap.setOption("reuseAddr", true);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true); Channel channel = bootstrap.bind(new InetSocketAddress(8080)); allChannels.add(channel);
//waitForShutdownCommand(); this is a imaginary logic:for instance
//when there is accepted connection we close this server ;
if(allChannels.size() >=2){
ChannelGroupFuture f = allChannels.close();
f.awaitUninterruptibly();
factory.releaseExternalResources();
}
}
}
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelHandler; public class TimeServerHandler extends SimpleChannelHandler{
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
Channel ch = e.getChannel();
ChannelBuffer time = ChannelBuffers.buffer(4); //sizeof int
time.writeInt((int)(System.currentTimeMillis()/1000L + 2208988800L)); ChannelFuture cf = ch.write(time);
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Channel ch = future.getChannel();
ch.close();
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
e.getCause().printStackTrace();
Channel c = e.getChannel();
c.close();
}
}
Netty入门实例及分析的更多相关文章
- 网络编程Netty入门:ByteBuf分析
目录 Netty中的ByteBuf优势 NIO使用的ByteBuffer有哪些缺点 ByteBuf的优势和做了哪些增强 ByteBuf操作示例 ByteBuf操作 简单的Demo示例 堆内和堆外内存 ...
- netty入门实例
TimeServer.java package netty.timeserver.server; import io.netty.bootstrap.ServerBootstrap; import i ...
- 网络编程Netty入门:EventLoopGroup分析
目录 Netty线程模型 代码示例 NioEventLoopGroup初始化过程 NioEventLoopGroup启动过程 channel的初始化过程 Netty线程模型 Netty实现了React ...
- GEF入门实例_总结_04_Eclipse插件启动流程分析
一.前言 本文承接上一节:GEF入门实例_总结_03_显示菜单和工具栏 注意到app目录下的6个类文件. 这6个文件对RCP应用程序而言非常重要,可能我们现在对这几个文件的理解还是云里雾里,这一节我们 ...
- (入门篇 NettyNIO开发指南)第三章-Netty入门应用
作为Netty的第一个应用程序,我们依然以第2章的时间服务器为例进行开发,通过Netty版本的时间服务报的开发,让初学者尽快学到如何搭建Netty开发环境和!运行Netty应用程序. 如果你已经熟悉N ...
- Netty入门(三):EventLoop
前言 Netty系列索引: 1.Netty入门(一):ByteBuf 2.Netty入门(二):Channel IO相关: 1.Java基础(一):I/O多路复用模型及Linux中的应用 上文提到,早 ...
- Netty入门(二):Channel
前言 Netty系列索引: 1.Netty入门(一):ByteBuf 2.Netty入门(二):Channel 在Netty框架中,Channel是其中之一的核心概念,是Netty网络通信的主体,由它 ...
- Omnet++ 4.0 入门实例教程
http://blog.sina.com.cn/s/blog_8a2bb17d01018npf.html 在网上找到的一个讲解omnet++的实例, 是4.0下面实现的. 我在4.2上试了试,可以用. ...
- jquery实战第一讲---概述及其入门实例
就在5月28号周四下午五点的时候,接到xxx姐姐的电话,您是xxx吗?准备一下,周五上午八点半去远洋面试,一路风尘仆仆,颠颠簸簸,由于小编晕车,带着晕晕乎乎的脑子,小编就稀里糊涂的去面试了,温馨提醒, ...
随机推荐
- FileOutputSteam入门
FileOutputSteam 字节输入流 从控制台将字节保存到本地硬盘 package com.isoftstone.io; import java.io.FileOutputStream; imp ...
- SQL Server 3
一.数据压缩 1.行压缩 行压缩可将固定长度类型存储为可变长度存储类型.例如,使用char(100)数据列存储字符串“SQL Server 2012”,压缩后只需要存放15个字符.(这种压缩模式,将对 ...
- echarts地图定时切换散点及多图表级联联动
本文目录 1. 摘要 2.引入ECharts以及地图相关json 3. 界面布局 4. js实现图形布局 5.定时循环jquery实现 6. 总结 1. 摘要 最近做项目遇到个统计相关需求,一个页面 ...
- 工作流调度器azkaban2.5.0的安装和使用
为什么需要工作流调度系统 一个完整的数据分析系统通常都是由大量任务单元组成: shell脚本程序,java程序,mapreduce程序.hive脚本等 各任务单元之间存在时间先后及前后依赖关系 为了很 ...
- NAT虚拟网络配置
NAT虚拟网络配置(Linux能上网) 1.先设置虚拟机的虚拟网络,设置里面的子网ip和网关ip地址: 有两种方式:①setup命令(不选DHCP,因为它是动态分配IP地址的) ②vi /etc/s ...
- 【转】HTML5 API——无刷新更新地址 history.pushState/replaceState 方法
(window.location)在通过JavaScript更改以后,浏览器都会通过刷新来到达你更改后的URL(location的意思就是位 置..) 而在JavaScript MVC开始流行之后,通 ...
- ZOJ Monthly, March 2018 题解
[题目链接] A. ZOJ 4004 - Easy Number Game 首先肯定是选择值最小的 $2*m$ 进行操作,这些数在操作的时候每次取一个最大的和最小的相乘是最优的. #include & ...
- 利用HTML5定位功能,实现在百度地图上定位(转)
原文:利用HTML5定位功能,实现在百度地图上定位 代码如下: 测试浏览器:ie11定位成功率100%,Safari定位成功率97%,(add by zhj :在手机上测试(用微信内置浏览器打开),无 ...
- 001.RAID简介
一 RAID介绍 独立磁盘冗余数组(RAID, Redundant Array of Independent Disks),旧称廉价磁盘冗余数组(RAID,Redundant Array of Ine ...
- 前端页面重构技巧总结TIP【持续更新...】
本文均为项目实战经验,要求兼容至IE8,所以以下内容均为兼容代码,欢迎各位小伙伴批评指教.其实重构页面是一门学问,看似简单,却暗藏很多学问.实际项目中页面的重构有以下几点最基本需求: 1.需要使用合理 ...