- 浏览: 984126 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (826)
- 硬件 (8)
- 软件 (24)
- 软件工程 (34)
- JAVA (229)
- C/C++/C# (77)
- JavaScript (8)
- PHP (1)
- Ruby (3)
- MySQL (14)
- 数据库 (19)
- 心情记事 (12)
- 团队管理 (19)
- Hadoop (1)
- spring (22)
- mybatis(ibatis) (7)
- tomcat (16)
- velocity (0)
- 系统架构 (6)
- JMX (8)
- proxool (1)
- 开发工具 (16)
- python (10)
- JVM (27)
- servlet (5)
- JMS (26)
- ant (2)
- 设计模式 (5)
- 智力题 (2)
- 面试题收集 (1)
- 孙子兵法 (16)
- 测试 (1)
- 数据结构 (7)
- 算法 (22)
- Android (11)
- 汽车驾驶 (1)
- lucene (1)
- memcache (12)
- 技术架构 (7)
- OTP-Erlang (7)
- memcached (17)
- redis (20)
- 浏览器插件 (3)
- sqlite (3)
- Heritrix (9)
- Java线程 (1)
- scala (0)
- Mina (6)
- 汇编 (2)
- Netty (15)
- libevent (0)
- CentOS (12)
- mongod (5)
- mac os (0)
最新评论
-
kingasdfg:
你这里面存在一个错误添加多个任务 应该是这样的 /** * ...
Quartz的任务的临时启动和暂停和恢复【转】 -
kyzeng:
纠正一个错误,long型对应的符号是J,不是L。
Jni中C++和Java的参数传递 -
zhaohaolin:
抱歉,兄弟,只是留下作记录,方便学习,如果觉得资料不好,可以到 ...
netty的个人使用心得【转】 -
cccoooccooco:
谢谢!自己一直以为虚机得使用网线才可以与主机连接呢。。
主机网卡无网线连接与虚拟机通信 -
yuqilin001:
要转别人的东西,请转清楚点嘛,少了这么多类,误人子弟
netty的个人使用心得【转】
Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。 如果需要客户端和服务器端沟通 分别都需要编写一个 实现了SimpleChannelHandler接口的类,其中类中需要重写的主要方法为 channelConnected() and channelOpen() 这两个方法为 当客户端链接到服务器端得时候和 客户端 channel被创建出来的时候所调用的 channelDisconnected and channelClosed() 对应上面的两个方法 exceptionCaught 可以获得 对应handler端(服务器或客户端)的异常信息 messageReceived 每个 客户端 发送的信息后 将调用此方法 当编写完某端得程序后(客户端或服务器端) 将编写好的handler需要配置在 实现了ChannelPipelineFactory的类里,ChannelPipelineFactory中有一个需要实现的方法getPipeline将写好的handler配置到其中,在这个 工厂里 可能要添加很多东西 比如说 编解码器,心跳等。。。。 如需要自定义编解码器需要继承:LengthFieldBasedFrameDecoder(解码),OneToOneEncoder(编码) 编解码器(encode,decode) encode为 调用messageReceived 方法之后调用的方法,则decode方法为 messageReceived 之前调用的方法 ,用于处理自定义包协议的解析于编辑 心跳: 当客户端socket在非正常情况家掉线,如: 断网,断电等特殊问题的时候, 客户端的channel对象不会自动关闭,需要一直接收到客户端的消息,从而判断是否可以和对象构成通信。。 如果 发现客户端空闲时间过长则视为掉线 服务端handler代码如下 package com.djyou.server; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; public static final ChannelGroup channelGroup = new DefaultChannelGroup(); @Override @Override @Override @Override pieplelineFactory里的代码为 package com.djyou.server; public class ChatPipelineServerFactory implements ChannelPipelineFactory{ pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());//对应 //netty会定时扫描 空闲的channel } 心跳包的代码如下 import org.jboss.netty.channel.ChannelHandlerContext; 自定义解码器代码 package com.djyou.server; import org.jboss.netty.buffer.ChannelBuffer; public class Decode extends LengthFieldBasedFrameDecoder{ public Decode(int maxFrameLength, int lengthFieldOffset, @Override } 自定义编码器代码 package com.djyou.server; import org.jboss.netty.channel.Channel; public class Encode extends OneToOneEncoder{ @Override } package com.djyou.server; import java.net.InetSocketAddress; import org.jboss.netty.bootstrap.ServerBootstrap; public class ChatServer { Timer timer = new HashedWheelTimer(); bootstrap.bind(new InetSocketAddress(6666)); 客户端启动代码如下(除客户端启动代码意外 其余的东西都与服务器端一样 都需要编写对应的 编解码器,定时发送消息线程(10秒发个信息给服务端 确保channel不为空闲, 来对应心跳程序), 客户端的handler) package com.djyou.client; import java.io.BufferedReader; import org.jboss.netty.bootstrap.ClientBootstrap; import com.djyou.protoBufModel.Message; public class ChatClient { // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap(factory); // Start the connection attempt. // Wait until the connection attempt succeeds or fails. // Read commands from the stdin. // We should shut down all thread pools here to exit normally.
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ChildChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
public class ChatServerHandler extends SimpleChannelHandler{
public int id;
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
System.out.println("进来一个");
}
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Logger.getAnonymousLogger().info(e.getCause().getMessage());
ctx.getChannel().close();
// TODO Auto-generated method stub
//super.exceptionCaught(ctx, e);
}
public void childChannelClosed(ChannelHandlerContext ctx,
ChildChannelStateEvent e) throws Exception {
super.childChannelClosed(ctx, e);
}
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
System.out.println(this.id++);
//google protocol解码后返回为 ChannelBuffer类型
if(!(e.getMessage() instanceof ChannelBuffer)) return;
//获得 消息对象
ChannelBuffer channelBuffer = (ChannelBuffer)e.getMessage();
//MessageInfo info = Message.MessageInfo.newBuilder().mergeFrom(channelBuffer.copy().array()).build();
//写回给客户端
e.getChannel().write(channelBuffer);
}
}
import static org.jboss.netty.channel.Channels.*;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.Timer;
private Timer timer;
public ChatPipelineServerFactory(Timer timer){
this.timer = timer;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
//添加netty默认支持的 编解码器(可自动添加包头,并处理粘包问题)
pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());//此对象为 netty默认支持protocolbuf的编解码器
pipeline.addLast("timeout", new IdleStateHandler(timer, 10, 10, 0));//此两项为添加心跳机制 10秒查看一次在线的客户端channel是否空闲,IdleStateHandler为netty jar包中提供的类
pipeline.addLast("hearbeat", new Heartbeat());//此类 实现了IdleStateAwareChannelHandler接口
//pipeline.addLast("frameDecoder", new ProtobufDecoder(Message.MessageInfo.getDefaultInstance()));
//pipeline.addLast("frameEncoder", new ProtobufEncoder());//
pipeline.addLast("handler", new ChatServerHandler());//将编写好的服务器端的handler添加到这里
return pipeline;
}
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
public class Heartbeat extends IdleStateAwareChannelHandler{
int i = 0;
@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
throws Exception {
// TODO Auto-generated method stub
super.channelIdle(ctx, e);
if(e.getState() == IdleState.WRITER_IDLE)
i++;
if(i==3){
e.getChannel().close();
System.out.println("掉了。");
}
}
}
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
int lengthFieldLength) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
// TODO Auto-generated constructor stub
}
protected Object decode(ChannelHandlerContext ctx, Channel channel,
ChannelBuffer buffer) throws Exception {
ChannelBuffer buffs = (ChannelBuffer)super.decode(ctx, channel, buffer);
return buffs;
}
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
protected Object encode(ChannelHandlerContext ctx, Channel channel,
Object msg) throws Exception {
// TODO Auto-generated method stub
return null;
}
服务端启动代码
import java.util.concurrent.Executors;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
public static void main(String[] args) {
ChannelFactory factory = new NioServerSocketChannelFactory(Executors
.newCachedThreadPool(), Executors.newCachedThreadPool(),
Runtime.getRuntime().availableProcessors() + 1);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChatPipelineServerFactory(timer));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress", true);
}
}
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import com.djyou.protoBufModel.Message.MessageInfo;
public static void main(String[] args) throws Exception{
String host = "localhost";
int port = 6666;
ChannelFactory factory =
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ChatPipelineClientFactory cpcf = new ChatPipelineClientFactory();
bootstrap.setPipelineFactory(cpcf);
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
Channel channel = future.awaitUninterruptibly().getChannel();
if (!future.isSuccess()) {
future.getCause().printStackTrace();
System.exit(0);
}
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// for (;;) {
// String line = in.readLine();
// if (line == null) {
// break;
// }
//创建Builder
MessageInfo.Builder builder = MessageInfo.newBuilder();
builder.addBody(Message.Body.newBuilder().setKey("message").setValue("你在干什么?" + "/n").build());
//创建 赋值结束的 Build 并生成 MessageInfo对象
MessageInfo messageInfo = builder.build();
//将messageInfo转换为字节
byte[] messageByte = messageInfo.toByteArray();
//获得此对象的长度
ChannelBuffer channelBuffer = ChannelBuffers.buffer(messageByte.length);
//将 获得到的数组写入 channelBuffer中
channelBuffer.writeBytes(messageByte);
//发送到服务器端
for(int i = 0; i < 10;i++){
lastWriteFuture = channel.write(channelBuffer);
}
if (lastWriteFuture != null) {
lastWriteFuture.awaitUninterruptibly();
}
// }
// Thread.sleep(50000);
// Wait until all messages are flushed before closing the channel.
Thread.sleep(50000);
// Close the connection. Make sure the close operation ends because
// all I/O operations are asynchronous in Netty.
channel.close().awaitUninterruptibly();
// However, it is just fine to call System.exit(0) because we are
// finished with the business.
System.exit(0);
}
}
评论
发表评论
-
调试jdk中的源码,查看jdk局部变量
2013-06-15 23:30 1009调试jdk中的源码,查看jdk局部变量 2012-04 ... -
Reactor模式和NIO<转>
2013-05-27 14:20 837本文可看成是对Doug Lea Scalable IO in ... -
Eclipse快捷键 10个最有用的快捷键<转>
2013-04-11 23:28 1005Eclipse中10个最有用的快捷键组合 一个Eclip ... -
Lucene 3.6 中文分词、分页查询、高亮显示等
2012-12-09 23:35 17681、准备工作 下载lucene 3.6.1 : htt ... -
Maven实战(九)——打包的技巧(转)
2012-10-12 00:41 897“打包“这个词听起 ... -
基于Maven的web工程如何配置嵌入式Jetty Server开发调试环境(转)
2012-10-12 00:28 8671、首先在web工程的POM文件里添加依赖jar包如下: ... -
轻轻松松学Solr(1)--概述及安装[转]
2012-09-18 14:59 946概述 这段时间对企 ... -
分析Netty工作流程[转]
2012-09-04 19:02 842下面以Netty中Echo的例 ... -
让eclipse在ubuntu下面好看一点
2012-03-27 10:17 880<p> </p> <h1 cla ... -
zookeeper安装和应用场合(名字,配置,锁,队列,集群管理)[转]
2012-01-12 17:59 1612安装和配置详解 本文 ... -
Jakarta-Common-BeanUtils使用笔记[转]
2012-01-10 14:13 1119Jakarta-Common-BeanUtils ... -
一个关于Java Thread wait(),notify()的实用例【转】
2012-01-07 16:05 981///// // ProducerConsume ... -
Java基础:Java中的 assert 关键字解析【转】
2012-01-06 19:50 971J2SE 1.4在语言上提供了 ... -
一篇不错的讲解Java异常的文章(转载)----感觉很不错,读了以后很有启发[转]
2012-01-06 15:02 1215六种异常处理的陋习 ... -
如何解决HP QC(Quality Center)在Windows 7下不能工作的问题
2011-12-26 10:48 1535HP QC(Quantity Center) 是一款不错的测 ... -
JAVA读写文件,中文乱码 【转】
2011-12-19 23:43 2069最近在做HTML静态生成,需要从硬盘上把模版文件的内容读出来。 ... -
Java 6 JVM参数选项大全(中文版)【转】
2011-12-19 19:51 924Java 6 JVM参数选项大全(中文版) 作者 ... -
使用assembly plugin实现自定义打包【转】
2011-12-13 01:58 923在上一篇文章中,讨论到在对maven的机制不熟悉的情况下,为了 ... -
使用maven ant task实现非标准打包[转]
2011-12-13 01:56 1002maven很强大,但是总有些事情干起来不是得心应手,没有使用a ... -
Java日期转换SimpleDateFormat格式大全【转】
2011-12-08 20:22 126124小时制时间 显示: public clas ...
相关推荐
Netty实战
Netty的UDP通信心得
Netty在Android开发中的应用实战系列(二)——— Encoder | Decoder | Handler 的使用:https://azhon.blog.csdn.net/article/details/100831777 Netty在Android开发中的应用实战系列(三)——— 心跳处理 | 断线...
netty部分解析
Netty使用与实现.pdf
NettyDemo Netty使用实例,对象传递调用; LineBasedFrameDecoder + 消息中得换行符;解决TCP 粘包问题; Java序列化方案编解码对比;对象调用方案
在公司做项目的时候发现用Netty进行TCP/IP通信的Netty客户端接收到的数据进制乱码,经过摸索,终于成功解决了这个鸡肋的问题
主要是netty长连接在Android中的使用,demo只是简单的实现了客户端和服务端的数据交互。如果要使用还需要完善很多细节。
netty通信时经常和底层数据交互,C语言和java的数据类型和范围不同,通信时需要转化或兼容,附件为字节码、进制常用的转换类。
Netty中使用WebSocket实现服务端与客户端的长连接通信发送消息示例代码;Netty中使用WebSocket实现服务端与客户端的长连接通信发送消息示例代码;Netty中使用WebSocket实现服务端与客户端的长连接通信发送消息示例代码
本资料是使用netty4来进行对象的传输的demo ,并对这个通信做了封装,方便用户的使用。
这个小程序使用netty5进行udp网络通讯,客户端有两种,1:用netty5类库发送DatagramPacket和接收 2:直接使用DatagramSocket发送接收DatagramPacket 先运行netty_server的QuoteOfTheMomentServer, 在运行netty_...
使用Netty, Disruptor处理实时外汇报价
使用netty进行rtsp服务端开发 一个使用netty写的rtsp服务器。 目前支持H264、H265、 AAC格式的流文件上传与存储。 H264、H265、AAC格式流文件的播放
java中使用netty包常见以及经常用到类说明: netty客户端配置及参数填写,常见类使用; netty服务端配置及参数填写,常见类使用;
Android Netty的简单使用,详情请看博客:https://blog.csdn.net/yuzhiqiang_1993/article/details/84390605
Android Studio 开发Netty网络访问框架,实现了客户端、服务端两种访问方式,支持发送心跳数据,使用Handler实现外部数据交互,有调用Demo,在实际项目中使用暂时没有问题
netty 物联网iot中mqtt 服务器端开发,主要是使用技术springboot+mqtt3.1.1+netty
spring+netty+mybatis整合实例 实现一个简单的socket服务,启动服务后,客户端发送一条消息,服务端从数据库查询数据并返回给客户端。
Netty基础,用于学习Netty,参考黑马程序员的netty教程