netty9---使用编码解码器
客户端:
- package com.client;
- import java.net.InetSocketAddress;
- import java.util.Scanner;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import org.jboss.netty.bootstrap.ClientBootstrap;
- import org.jboss.netty.channel.Channel;
- import org.jboss.netty.channel.ChannelFuture;
- 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;
- import com.cn.codc.RequestEncoder;
- import com.cn.codc.ResponseDecoder;
- import com.cn.model.Request;
- import com.cn.module.fuben.request.FightRequest;
- /**
- * netty客户端入门
- */
- public class Client {
- public static void main(String[] args) throws InterruptedException {
- //服务类
- ClientBootstrap bootstrap = new ClientBootstrap();
- //线程池
- ExecutorService boss = Executors.newCachedThreadPool();
- ExecutorService worker = Executors.newCachedThreadPool();
- //socket工厂
- bootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));
- //管道工厂
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- @Override
- public ChannelPipeline getPipeline() throws Exception {
- ChannelPipeline pipeline = Channels.pipeline();
- pipeline.addLast("decoder", new ResponseDecoder());//Response解码器
- pipeline.addLast("encoder", new RequestEncoder());//Request编码器
- pipeline.addLast("hiHandler", new HiHandler());//通过ResponseDecoder解码的是一个Response对象。
- return pipeline;
- }
- });
- //连接服务端
- ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10101));
- Channel channel = connect.sync().getChannel();
- System.out.println("client start");
- Scanner scanner = new Scanner(System.in);
- while(true){
- System.out.println("请输入");
- int fubenId = Integer.parseInt(scanner.nextLine());
- int count = Integer.parseInt(scanner.nextLine());
- FightRequest fightRequest = new FightRequest();
- fightRequest.setFubenId(fubenId);
- fightRequest.setCount(count);
- Request request = new Request();
- request.setModule((short) 1);//请求第一个模块的
- request.setCmd((short) 1);
- request.setData(fightRequest.getBytes());//fightRequest是数据体data
- //发送请求
- channel.write(request);
- }
- }
- }
- package com.client;
- import org.jboss.netty.channel.ChannelHandlerContext;
- import org.jboss.netty.channel.ChannelStateEvent;
- import org.jboss.netty.channel.ExceptionEvent;
- import org.jboss.netty.channel.MessageEvent;
- import org.jboss.netty.channel.SimpleChannelHandler;
- import com.cn.model.Response;
- import com.cn.model.StateCode;
- import com.cn.module.fuben.request.FightRequest;
- import com.cn.module.fuben.response.FightResponse;
- /**
- * 消息接受处理类
- */
- public class HiHandler extends SimpleChannelHandler {
- /**
- * 接收消息
- */
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
- Response message = (Response)e.getMessage();//解码出来的之后是Response对象,然后进行业务处理
- if(message.getModule() == 1){
- if(message.getCmd() == 1){
- FightResponse fightResponse = new FightResponse();
- fightResponse.readFromBytes(message.getData());
- System.out.println("gold:" + fightResponse.getGold());
- }else if(message.getCmd() == 2){
- }
- }else if (message.getModule() == 1){
- }
- }
- /**
- * 捕获异常
- */
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
- System.out.println("exceptionCaught");
- super.exceptionCaught(ctx, e);
- }
- /**
- * 新连接
- */
- @Override
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("channelConnected");
- super.channelConnected(ctx, e);
- }
- /**
- * 必须是链接已经建立,关闭通道的时候才会触发
- */
- @Override
- public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("channelDisconnected");
- super.channelDisconnected(ctx, e);
- }
- /**
- * channel关闭的时候触发
- */
- @Override
- public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("channelClosed");
- super.channelClosed(ctx, e);
- }
- }
服务端:
- package com.server;
- import java.net.InetSocketAddress;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import org.jboss.netty.bootstrap.ServerBootstrap;
- 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.NioServerSocketChannelFactory;
- import org.jboss.netty.handler.codec.string.StringDecoder;
- import org.jboss.netty.handler.codec.string.StringEncoder;
- import com.cn.codc.RequestDecoder;
- import com.cn.codc.ResponseEncoder;
- /**
- * netty服务端入门
- */
- public class Server {
- public static void main(String[] args) {
- //服务类
- ServerBootstrap bootstrap = new ServerBootstrap();
- //boss线程监听端口,worker线程负责数据读写
- ExecutorService boss = Executors.newCachedThreadPool();
- ExecutorService worker = Executors.newCachedThreadPool();
- //设置niosocket工厂
- bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));
- //设置管道的工厂
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- @Override
- public ChannelPipeline getPipeline() throws Exception {
- ChannelPipeline pipeline = Channels.pipeline();
- pipeline.addLast("decoder", new RequestDecoder());//Request的解码器
- pipeline.addLast("encoder", new ResponseEncoder());//Response的编码器
- pipeline.addLast("helloHandler", new HelloHandler());
- return pipeline;
- }
- });
- bootstrap.bind(new InetSocketAddress(10101));
- System.out.println("start!!!");
- }
- }
- package com.server;
- import org.jboss.netty.channel.ChannelHandlerContext;
- import org.jboss.netty.channel.ChannelStateEvent;
- import org.jboss.netty.channel.ExceptionEvent;
- import org.jboss.netty.channel.MessageEvent;
- import org.jboss.netty.channel.SimpleChannelHandler;
- import com.cn.model.Request;
- import com.cn.model.Response;
- import com.cn.model.StateCode;
- import com.cn.module.fuben.request.FightRequest;
- import com.cn.module.fuben.response.FightResponse;
- /**
- * 消息接受处理类
- */
- public class HelloHandler extends SimpleChannelHandler {
- /**
- * 接收消息
- */
- @Override
- public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
- Request message = (Request)e.getMessage();
- if(message.getModule() == 1){
- if(message.getCmd() == 1){
- FightRequest fightRequest = new FightRequest();
- fightRequest.readFromBytes(message.getData());
- System.out.println("fubenId:" +fightRequest.getFubenId() + " " + "count:" + fightRequest.getCount());
- //回写数据
- FightResponse fightResponse = new FightResponse();
- fightResponse.setGold(9999);
- Response response = new Response();
- response.setModule((short) 1);
- response.setCmd((short) 1);
- response.setStateCode(StateCode.SUCCESS);
- response.setData(fightResponse.getBytes());
- ctx.getChannel().write(response);
- }else if(message.getCmd() == 2){
- }
- }else if (message.getModule() == 1){
- }
- }
- /**
- * 捕获异常
- */
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
- System.out.println("exceptionCaught");
- super.exceptionCaught(ctx, e);
- }
- /**
- * 新连接
- */
- @Override
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("channelConnected");
- super.channelConnected(ctx, e);
- }
- /**
- * 必须是链接已经建立,关闭通道的时候才会触发
- */
- @Override
- public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("channelDisconnected");
- super.channelDisconnected(ctx, e);
- }
- /**
- * channel关闭的时候触发
- */
- @Override
- public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
- System.out.println("channelClosed");
- super.channelClosed(ctx, e);
- }
- }
网络传的是字节数据不是字符。
Netty之自定义数据包协议:
give me a coffee give me a tea (2条信息)
give me a coffeegive me a tea 粘包现象(2条信息粘在一起)
give me
a coffeegive me a tea 分包现象(第一条消息分开了,第一条后部分又粘到了第二条消息)
粘包和分包出现的原因是:没有一个稳定数据结构(没有确定一个请求传递哪些数据)
分割符:
give me a coffee|give me a tea|
give me a coffee|
give me a tea|
长度 + 数据:
16give me a coffee13give me a tea(读取16个就封装成一个请求,投递到业务层去)
16give me a coffee
13give me a tea
netty9---使用编码解码器的更多相关文章
- libZPlay 音频编码解码器库
libZPlay 音频编码解码器库 http://www.oschina.net/p/libzplay libZPlay 播放音乐并显示 FFT 图形 :http://www.oschina.net/ ...
- [转]用C#实现的条形码和二维码编码解码器
条形码的标准: 条形码的标准有ENA条形码.UPC条形码.二五条形码.交叉二五条形码.库德巴条形码.三九条形码和128条形码等,而商品上最常使用的就是EAN商品条形码.EAN商品条形码亦称通用商品条形 ...
- 用C#实现的条形码和二维码编码解码器
本文主要介绍可以在C#中使用的1D/2D编码解码器.条形码的应用已经非常普遍,几乎所有超市里面的商品上面都印有条形码:二维码也开始应用到很多场合,如火车票有二维码识别.网易的首页有二维码图标,用户只需 ...
- CVE-2010-2553 Microsoft Windows Cinepak 编码解码器解压缩漏洞 分析
Microsoft Windows是微软发布的非常流行的操作系统. Microsoft Windows XP SP2和SP3,Windows Vista SP1和SP2,以及Win ...
- 13-H.264编码解码器的无线应用:1080P60 3D无线影音传输器
H.264编码解码器的无线应用:1080P60 3D无线影音传输器 一.应用领域 家庭媒体娱乐中心 新闻现场采访 无线3D投影机 高清视频会议终端无线延长器 教学,医疗示教 考古,高档商业区域,监狱等 ...
- netty系列之:自定义编码解码器
目录 简介 自定义编码器 自定义解码器 添加编码解码器到pipeline 计算2的N次方 总结 简介 在之前的netty系列文章中,我们讲到了如何将对象或者String转换成为ByteBuf,通过使用 ...
- netty系列之:netty中的懒人编码解码器
目录 简介 netty中的内置编码器 使用codec要注意的问题 netty内置的基本codec base64 bytes compression json marshalling protobuf ...
- netty系列之:netty中常用的字符串编码解码器
目录 简介 netty中的字符串编码解码器 不同平台的换行符 字符串编码的实现 总结 简介 字符串是我们程序中最常用到的消息格式,也是最简单的消息格式,但是正因为字符串string太过简单,不能附加更 ...
- netty系列之:netty中常用的对象编码解码器
目录 简介 什么是序列化 重构序列化对象 序列化不是加密 使用真正的加密 使用代理 Serializable和Externalizable的区别 netty中对象的传输 ObjectEncoder O ...
- DIOCP之注册编码解码器与ClientContext
FTcpServer.registerCoderClass(TIOCPStreamDecoder, TIOCPStreamEncoder);//注册编码器与解码器 FTcpServer.registe ...
随机推荐
- ios开发之--NSMutableParagraphStyle与NSParagraphStyle的使用
在ios6以后,苹果官方建议用“- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options ...
- ios开发之 --调用系统的页面,显示中文
在开发的过程中,我们会接入很多的sdk,比如相机,相册,是否允许获取位置等,大多数的情况下是默认显示英文, 在plist文件里面添加一个key就可以了,如下图: key:Localization na ...
- Android 网卡地址Mac Wifi文件
1./system/etc/firmware/ti-connectivity/wl1271-nvs.bin的文件 2./data/etc/wifi/fw文件 3./data/nvram/APCFG/A ...
- JB开发之问题汇总 [jailbreak,越狱技术]
1.升级到Mac 10.9.1,Xcode 升级到5出现的问题: 1)升级前要做的事情: ①升级/重新安装iOSOpenDev,在终端输入 xcode-select --switch (xcode_d ...
- Linux命令之乐--curl
参数: -I 获取头部信息 -s/--silent Silent mode. Don't output anything 沉默模式 --connect-timeout <secon ...
- 指针与C++基本原理
面向对象编程与传统的过程性编程的区别在于,OOP强调的是在运行阶段(而不是编译阶段)进行决策.运行阶段指的是程序正在运行时,编译阶段指的是编译器将程序组合起来时.运行阶段决策就好比度假时,选择参观那些 ...
- 扩展jquery scroll事件,支持 scroll start 和 scroll stop
效果预览: github: https://besswang.github.io/webapp-scroll/ 参考地址: http://www.ghugo.com/special-scroll-ev ...
- Linux Tar 命令简明教程
Tar 命令经常用但是它的各种参数又总是记不住,因此彻底梳理了一下,再也不会忘记. Tar 是 Linux 中的(压缩)归档工具. 归档的意思与打包相同,就是把文件或目录或者多个文件和目录打包为一个文 ...
- 170419、Centos7下完美安装并配置mysql5.6
首先跟各位说声抱歉,原计划说每天一篇博文,最近由于实在太忙,封闭式开发一个项目,没有时间写博文,望大家见谅!!! 由于公司要搭建分布式服务,我把最近我所用到或者学习的技术或者遇到的问题跟大家分享一下! ...
- 160422、Highcharts后台获取数据
而我这次做的是趋势图,涉及到动态刷新,做的过程还是花了一番功夫的,也补充和巩固了一点js的知识,为了纪念,把过程记录一下: 首先,是引入HIghcharts绘图相关的js文件和jQuery.js. 接 ...