netty-time-Second Solution

2024-04-12 23:58
文章标签 netty solution time second

本文主要是介绍netty-time-Second Solution,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

TimeServer、TimeServerHandler同上篇文章。

package org.q.netty.time2;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 {private static final String host = "127.0.0.1";private static final int port = 9999;public static void main(String[] args) {ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());ClientBootstrap bootstrap = new ClientBootstrap(factory);bootstrap.setPipelineFactory(new ChannelPipelineFactory() {public ChannelPipeline getPipeline() throws Exception {return Channels.pipeline(new TimeDecoder(), new TimeClientHandler());}});bootstrap.setOption("tcpNoDelay", true);bootstrap.setOption("keepAlive", true);bootstrap.connect(new InetSocketAddress(host, port));}}

package org.q.netty.time2;import java.text.SimpleDateFormat;
import java.util.Date;import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
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 {ChannelBuffer buf = ChannelBuffers.dynamicBuffer(4);@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)throws Exception {e.getCause().printStackTrace();e.getChannel().close();}@Overridepublic void messageReceived(ChannelHandlerContext ctx, MessageEvent e)throws Exception {ChannelBuffer buf = (ChannelBuffer) e.getMessage();long currentTimeMillis = buf.readInt() * 1000L;SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");Date date = new Date(currentTimeMillis);System.out.println(date);System.out.println(format.format(date));e.getChannel().close();}}

package org.q.netty.time2;import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;
import org.jboss.netty.handler.codec.replay.VoidEnum;public class TimeDecoder extends ReplayingDecoder<VoidEnum> {@Overrideprotected Object decode(ChannelHandlerContext ctx, Channel channel,ChannelBuffer buffer, VoidEnum state) throws Exception {return buffer.readBytes(4);}
}

FrameDecoder is an implementation of ChannelHandler which makes it easy to which deals with the fragmentation issue.

FrameDecoder calls decode method with an internally maintained cumulative buffer whenever new data is received.

If null is returned, it means there's not enough data yet. FrameDecoder will call again when there is a sufficient amount of data.

If non-null is returned, it means the decode method has decoded a message successfully. FrameDecoder will discard the read part of its internal cumulative buffer. Please remember that you don't need to decode multiple messages. FrameDecoder will keep calling the decoder method until it returns null.

 private void callDecode(ChannelHandlerContext context, Channel channel,ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception {while (cumulation.readable()) {int oldReaderIndex = cumulation.readerIndex();Object frame = decode(context, channel, cumulation);if (frame == null) {if (oldReaderIndex == cumulation.readerIndex()) {// Seems like more data is required.// Let us wait for the next notification.break;} else {// Previous data has been discarded.// Probably it is reading on.continue;}} else if (oldReaderIndex == cumulation.readerIndex()) {throw new IllegalStateException("decode() method must read at least one byte " +"if it returned a frame (caused by: " + getClass() + ")");}unfoldAndFireMessageReceived(context, remoteAddress, frame);}if (!cumulation.readable()) {this.cumulation = null;}}



If you are an adventurous person, you might want to try the ReplayingDecoder which simplifies the decoder even more. You will need to consult the API reference for more information though. 

private void callDecode(ChannelHandlerContext context, Channel channel, ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception {while (cumulation.readable()) {int oldReaderIndex = checkpoint = cumulation.readerIndex();Object result = null;T oldState = state;try {result = decode(context, channel, replayable, state);if (result == null) {if (oldReaderIndex == cumulation.readerIndex() && oldState == state) {throw new IllegalStateException("null cannot be returned if no data is consumed and state didn't change.");} else {// Previous data has been discarded or caused state transition.// Probably it is reading on.continue;}}} catch (ReplayError replay) {// Return to the checkpoint (or oldPosition) and retry.int checkpoint = this.checkpoint;if (checkpoint >= 0) {cumulation.readerIndex(checkpoint);} else {// Called by cleanup() - no need to maintain the readerIndex// anymore because the buffer has been released already.}}if (result == null) {// Seems like more data is required.// Let us wait for the next notification.break;}if (oldReaderIndex == cumulation.readerIndex() && oldState == state) {throw new IllegalStateException("decode() method must consume at least one byte " +"if it returned a decoded message (caused by: " +getClass() + ")");}// A successful decodeunfoldAndFireMessageReceived(context, result, remoteAddress);if (!cumulation.readable()) {this.cumulation.set(null);replayable = ReplayingDecoderBuffer.EMPTY_BUFFER;}}}



这篇关于netty-time-Second Solution的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/898594

相关文章

linux 下Time_wait过多问题解决

转自:http://blog.csdn.net/jaylong35/article/details/6605077 问题起因: 自己开发了一个服务器和客户端,通过短连接的方式来进行通讯,由于过于频繁的创建连接,导致系统连接数量被占用,不能及时释放。看了一下18888,当时吓到了。 现象: 1、外部机器不能正常连接SSH 2、内向外不能够正常的ping通过,域名也不能正常解析。

python内置模块datetime.time类详细介绍

​​​​​​​Python的datetime模块是一个强大的日期和时间处理库,它提供了多个类来处理日期和时间。主要包括几个功能类datetime.date、datetime.time、datetime.datetime、datetime.timedelta,datetime.timezone等。 ----------动动小手,非常感谢各位的点赞收藏和关注。----------- 使用datet

AtCoder Beginner Contest 370 Solution

A void solve() {int a, b;qr(a, b);if(a + b != 1) cout << "Invalid\n";else Yes(a);} B 模拟 void solve() {qr(n);int x = 1;FOR(i, n) FOR(j, i) qr(a[i][j]);FOR(i, n) x = x >= i ? a[x][i]: a[i][x];pr2(

【Netty】netty中都是用了哪些设计模式

对于工程师来说,掌握并理解运用设计模式,是非常重要的,但是除了学习基本的概念之外,需要结合优秀的中间件、框架源码学习其中的优秀软件设计,这样才能以不变应万变。 单例模式 单例模式解决的对象的唯一性,一般来说就是构造方法私有化、然后提供一个静态的方法获取实例。 在netty中,select用于处理CONTINUE、SELECT、BUSY_WAIT 三种策略,通过DefaultSelectStra

Java语言的Netty框架+云快充协议1.5+充电桩系统+新能源汽车充电桩系统源码

介绍 云快充协议+云快充1.5协议+云快充1.6+云快充协议开源代码+云快充底层协议+云快充桩直连+桩直连协议+充电桩协议+云快充源码 软件架构 1、提供云快充底层桩直连协议,版本为云快充1.5,对于没有对接过充电桩系统的开发者尤为合适; 2、包含:启动充电、结束充电、充电中实时数据获取、报文解析、Netty通讯框架、包解析工具、调试器模拟器软件等; 源码合作 提供完整云快充协议源代码

lua data time

local getTime = os.date(“%c”); 其中的%c可以是以下的一种:(注意大小写) %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., Sep

Netty源码解析9-ChannelHandler实例之MessageToByteEncoder

MessageToByteEncoder框架可见用户使用POJO对象编码为字节数据存储到ByteBuf。用户只需定义自己的编码方法encode()即可。 首先看类签名: public abstract class MessageToByteEncoder<I> extends ChannelOutboundHandlerAdapter 可知该类只处理出站事件,切确的说是write事件

Netty源码解析8-ChannelHandler实例之CodecHandler

编解码处理器作为Netty编程时必备的ChannelHandler,每个应用都必不可少。Netty作为网络应用框架,在网络上的各个应用之间不断进行数据交互。而网络数据交换的基本单位是字节,所以需要将本应用的POJO对象编码为字节数据发送到其他应用,或者将收到的其他应用的字节数据解码为本应用可使用的POJO对象。这一部分,又和JAVA中的序列化和反序列化对应。幸运的是,有很多其他的开源工具(prot

Netty源码解析7-ChannelHandler实例之TimeoutHandler

请戳GitHub原文: https://github.com/wangzhiwubigdata/God-Of-BigData TimeoutHandler 在开发TCP服务时,一个常见的需求便是使用心跳保活客户端。而Netty自带的三个超时处理器IdleStateHandler,ReadTimeoutHandler和WriteTimeoutHandler可完美满足此需求。其中IdleSt

Netty源码解析6-ChannelHandler实例之LoggingHandler

LoggingHandler 日志处理器LoggingHandler是使用Netty进行开发时的好帮手,它可以对入站\出站事件进行日志记录,从而方便我们进行问题排查。首先看类签名: @Sharablepublic class LoggingHandler extends ChannelDuplexHandler 注解Sharable说明LoggingHandler没有状态相关变量,