网络编程 -- 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. 服务器被ddos攻击?分析如何防止DDOS攻击?

    上周知名博主阮一峰的博客被DDOS攻击,导致网站无法访问而被迫迁移服务器的事情,引起了广大网友的关注及愤慨,包括小编的个人博客也曾接受过DDOS的“洗礼”,对此感同身受.所以,本文我们一起来了解下DD ...

  2. python:函数的高级特性

    很多语言中,都允许把函数本身做为参数,传递给其它参数:即所谓的高阶函数.python中也有类似特性: 一.map/reduce.filter.sorted hadoop里的map-reduce思想在p ...

  3. ios 类别(category)

    定义 类别(category)是Objective-C语言的新特性,为现有的类添加新方法的方式.局限性:1.无法添加新的实例变量.2.与类本身的方法名称冲突.当名称冲突时,类别具有更高的优先级.作用: ...

  4. 微软BI 之SSIS 系列 - 在 SSIS 中使用 Web Service 以及 XML 解析

    开篇介绍 Web Service 的用途非常广几乎无处不在,像各大门户网站上的天气预报使用到的第三方 Web Service API,像手机客户端和服务器端的交互等都可以通过事先设计好的 Web Se ...

  5. swift3 单例写法

    import UIKit class SingleOnce { // 单例 static let shared = SingleOnce.init() private init(){} // 其他方法 ...

  6. SQL Server 数据库基础笔记分享(上)

    前言 本文是个人学习SQL Server 数据库时的以往笔记的整理,内容主要是对数据库的基本增删改查的SQL语句操作和约束,视图,存储过程,触发器的基本了解. 注:内容比较基础,适合入门者对SQL S ...

  7. React Native 设置RGBA背景色

    React Native 设置RGBA背景色: 可以先用Mac自带吸色工具,获取RGB值,然后设置背景如下: backgroundColor: 'rgba(52, 52, 52, 0.8)', 透明度 ...

  8. C#-MVC开发微信应用(3)--文本消息和图文消息的应答

    最近咨询微信的人很多,感觉这块也是一块商机,也为了演示SNF快速开发平台的优势,就用SNF快速开发平台开发出一套微信应用程序.使用<SNF.CodeGenerator>代码生成工具可以节省 ...

  9. qeephp 记录下

    百度百科: https://baike.baidu.com/item/qeephp/8328612?fr=aladdin 官方地址: http://www.qeephp.cn/app/index.ph ...

  10. 详解nginx 配置多个tomcat共用80端口

    场景:项目1放在tomcat1中,项目2放在tomcat2中,两个tomcat放在同一台服务器上,需要共享80端口访问注意:这里和集群部署是不同的,集群部署是一个项目放在多个tomcat中.这里通过n ...