网络编程 -- RPC实现原理 -- 目录

  啦啦啦

V2——Netty --

  new LengthFieldPrepender(2) : 设置数据包 2 字节的特征码

  new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2) :  65535 :数据包长度、0:分隔符偏移值、2:分隔符长度、0:数据包偏移值、2:数据包长度。

  Class : Server

package lime.pri.limeNio.netty.netty04;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.CharsetUtil;
import lime.pri.limeNio.netty.netty03.entity.User; public class Server { public static void main(String[] args) throws Exception {
ServerBootstrap serverBootstrap = new ServerBootstrap();
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
serverBootstrap.group(boss, worker);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldPrepender(2))
.addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2))
.addLast(new MessageToMessageCodec<ByteBuf, Object>() {
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
throws Exception {
out.add(Unpooled.buffer().writeBytes(JSON.toJSONString(msg,SerializerFeature.WriteClassName).getBytes(CharsetUtil.UTF_8)));
} @Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
throws Exception {
out.add(JSON.parse(msg.toString(CharsetUtil.UTF_8)));
}
}).addLast(new ChannelHandlerAdapter() { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("客户端(" + ctx.channel().remoteAddress() + ") 请求数据:" + msg);
ChannelFuture channelFuture = null; String request = (String) msg;
Calendar calendar = Calendar.getInstance();
if("Query Date".equalsIgnoreCase(request)){
for (int i = 1; i < 10; i++) {
calendar.set(Calendar.DAY_OF_MONTH, i);
channelFuture = ctx.writeAndFlush("当前系统时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
}
}else if("Query User".equalsIgnoreCase(request)){
for (int i = 1; i < 10; i++) {
channelFuture = ctx.writeAndFlush(new User(i,"lime_" + i,new Date()));
}
}else{
channelFuture = ctx.writeAndFlush("请求参数不正确");
} channelFuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
channelFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
channelFuture.addListener(ChannelFutureListener.CLOSE);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println(cause);
} });
} });
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(9999)).sync();
channelFuture.channel().closeFuture().sync();
boss.close();
worker.close();
}
}

  Class : Client

package lime.pri.limeNio.netty.netty04;

import java.net.InetSocketAddress;
import java.util.List; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature; import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.CharsetUtil; public class Client { public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
new Thread() {
{
setDaemon(false);
} public void run() {
try {
client();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
} private static void client() throws Exception {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup worker = new NioEventLoopGroup();
bootstrap.group(worker);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldPrepender(2))
.addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2))
.addLast(new MessageToMessageCodec<ByteBuf, Object>() {
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
throws Exception {
out.add(Unpooled.buffer().writeBytes(JSON.toJSONString(msg,SerializerFeature.WriteClassName).getBytes(CharsetUtil.UTF_8)));
} @Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
throws Exception {
out.add(JSON.parse(msg.toString(CharsetUtil.UTF_8)));
}
}).addLast(new ChannelHandlerAdapter() { /**
* 默认只捕获网络连接异常
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println(cause);
} /**
* 客户端发送经过JSON编码的byteBuf
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String request = null;
switch (0) {
case 0:
request = "Query Date";
break;
case 1:
request = "Query User";
break;
default:
request = "Query What?";
break;
}
ctx.writeAndFlush(request);
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("当前线程:" + Thread.currentThread() + " 服务端响应数据 --> " + msg);
} });
}
});
ChannelFuture channelFuture; channelFuture = bootstrap.connect(new InetSocketAddress(9999)).sync();
channelFuture.channel().closeFuture().sync();
worker.close();
}
}

  Console: Server

客户端(/192.168.229.1:6280) 请求数据:Query Date

  Console : Client

当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-01 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-02 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-03 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-04 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-05 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-06 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-07 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-08 21:42:08
当前线程:Thread[nioEventLoopGroup-0-1,10,main] 服务端响应数据 --> 当前系统时间:2017-06-09 21:42:08

啦啦啦

网络编程 -- RPC实现原理 -- Netty -- 迭代版本V4 -- 粘包拆包的更多相关文章

  1. 网络编程 -- RPC实现原理 -- Netty -- 迭代版本V1 -- 入门应用

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V1——Netty入门应用 Class : NIOServerBootStrap package lime.pri.limeNio.netty.ne ...

  2. 网络编程 -- RPC实现原理 -- Netty -- 迭代版本V2 -- 对象传输

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V2——Netty -- 使用序列化和反序列化在网络上传输对象:需要实现 java.io.Serializable 接口 只能传输( ByteBuf ...

  3. 网络编程 -- RPC实现原理 -- Netty -- 迭代版本V3 -- 编码解码

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V2——Netty -- pipeline.addLast(io.netty.handler.codec.MessageToMessageCodec ...

  4. 网络编程 -- RPC实现原理 -- 目录

    -- 啦啦啦 -- 网络编程 -- RPC实现原理 -- NIO单线程 网络编程 -- RPC实现原理 -- NIO多线程 -- 迭代版本V1 网络编程 -- RPC实现原理 -- NIO多线程 -- ...

  5. 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V1 -- 本地方法调用

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V1——RPC -- 本地方法调用:不通过网络 入门 1. RPCObjectProxy rpcObjectProxy = new RPCObjec ...

  6. 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V2 -- 本地方法调用 整合 Spring

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V2——RPC -- 本地方法调用 + Spring 1. 配置applicationContext.xml文件 注入 bean 及 管理 bean ...

  7. 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V3 -- 远程方法调用 整合 Spring

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V3——RPC -- 远程方法调用 及 null的传输 + Spring 服务提供商: 1. 配置 rpc03_server.xml 注入 服务提供 ...

  8. 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V4 -- 远程方法调用 整合 Spring 自动注册

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V4——RPC -- 远程方法调用 + Spring 自动注册 服务提供商: 1. 配置 rpc04_server.xml 注入 服务提供商 rpc ...

  9. 网络编程 -- RPC实现原理 -- NIO多线程 -- 迭代版本V1

    网络编程 -- RPC实现原理 -- 目录 啦啦啦 V1——设置标识变量selectionKey.attach(true);只处理一次(会一直循环遍历selectionKeys,占用CPU资源). ( ...

随机推荐

  1. print2flash文档在线预览应用(java,.net)

    一.背景 前段时间,LZ的boss突然给了出了这样一个需求:将原项目中的所有文章关联的附件TXT.PDF.office相关文件全部以flash的形式在网页上进行展示,便于预览.看似简单的需求,整个研发 ...

  2. linux 启动 Oracle 实例

    启动数据库实例,分为两步:第一步,启动监听:第二步,启动数据库实例. 一.如何启动数据库实例 1.进入到sqlplus启动实例 --“切换到oracle用户” su - oracle --“打开监听” ...

  3. 64位电脑上启动程序出现丢失MSVCR110.dll的解决办法

    启动程序报错如下: 无法启动此程序,因为计算机中丢失MSVCR110.dll.尝试重新安装该程序以解决此问题. 应该很容易就搜索到,缺少这样的dll文件,是没有安装Visual C++ Redistr ...

  4. 分布式文件系统---GlusterFS

    1.1 分布式文件系统 1.1.1 什么是分布式文件系统 相对于本机端的文件系统而言,分布式文件系统(英语:Distributed file system, DFS),或是网络文件系统(英语:Netw ...

  5. MDX Cookbook 11 - 计算 Year Over Year 增长 (同比计算) ParallelPeriod

    这一小节主要介绍如何在一个平行期间的度量值,当前值的对比对象是指当前值的上一年,上一个季度或者其它时间级别上与当前值同一时间点上的的那个对象.有一个非常常见的需求就是对比上一年同一个时间点的某个值来判 ...

  6. 每天一个linux命令(2):cd命令

    1.作用 cd(Change Directory 改变目录)命令用来切换工作目录至dirname. 其中dirName表示法可为绝对路径或相对路径.若目录名称省略,则变换至使用者的home direc ...

  7. shiny: Web Application Framework for R

    shiny: Web Application Framework for R 基于R语言的一个web框架,适用于数据分析与图表绘画展示类型的网站.

  8. 9.4 翻译系列:EF 6以及 EF Core中的NotMapped特性(EF 6 Code-First系列)

    原文链接:http://www.entityframeworktutorial.net/code-first/notmapped-dataannotations-attribute-in-code-f ...

  9. 转 HashMap 比较透彻的分析

    HashMap 的实现原理 原文: HashMap 的实现原理 众所周知,HashMap是用来存储Key-Value键值对的一种集合,这个键值对也叫做Entry,而每个Entry都是存储在数组当中,因 ...

  10. Socket网络编程--简单Web服务器(6)

    本来是想实现ssl连接的,但是弄了好久都不成功,就索性不做了,等以后有能力再做了.所以这一小节就是本次的最后一节了.就简单的说几个注意点. 1.加个配置文件 使用单例模式,使用一个类,该类保存一些信息 ...