mina 字节数组编解码器的写法 II
I 里面的写法不够严谨,这也是我之前说它简陋的主要原因,下面来个更加严谨、完整一点儿的:
ByteArrayEncoder.java
package org.bruce.mina.cpp.codec; import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.bruce.mina.cpp.util.NumberUtil; /**
* @author BruceYang
* 编写编码器的注意事项:
* 1、 mina 为 IoSession 写队列里的每个对象调用 ProtocolEncode.encode 方法。
* 因为业务处理器里写出的都是与编码器对应高层对象,所以可以直接进行类型转换。
* 2、从 jvm 堆分配 IoBuffer,最好避免使用直接缓存,因为堆缓存一般有更好的性能。
* 3、开发人员不需要释放缓存, mina 会释放。
* 4、在 dispose 方法里可以释放编码所需的资源。
*/
public class ByteArrayEncoder extends ProtocolEncoderAdapter { @Override
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
// TODO Auto-generated method stub
byte[] dataBytes = (byte[])message;
byte[] sizeBytes = NumberUtil.int2bytes(dataBytes.length); IoBuffer buffer = IoBuffer.allocate(256);
buffer.setAutoExpand(true); buffer.put(sizeBytes);
buffer.put(dataBytes); buffer.flip();
out.write(buffer);
out.flush(); buffer.free();
}
}
ByteArrayDecoder.java
package org.bruce.mina.cpp.codec; import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.bruce.mina.cpp.util.NumberUtil; /**
* @author BruceYang
* 字节数组解码器
*/
public class ByteArrayDecoder extends CumulativeProtocolDecoder { public boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {
// TODO Auto-generated method stub
if (in.remaining() > 0) {
// 有数据时,读取 4 字节判断消息长度
byte[] sizeBytes = new byte[4]; // 标记当前位置,以便 reset
in.mark(); // 读取前 4 个字节
in.get(sizeBytes); // NumberUtil 是自己写的一个 int 转 byte[] 的工具类
int size = NumberUtil.bytes2int(sizeBytes); if (size > in.remaining()) {
// 如果消息内容的长度不够,则重置(相当于不读取 size),返回 false
in.reset();
// 接收新数据,以拼凑成完整的数据~
return false; } else {
byte[] dataBytes = new byte[size];
in.get(dataBytes, 0, size);
out.write(dataBytes); if (in.remaining() > 0) {
// 如果读取内容后还粘了包,就让父类把剩下的数据再给解析一次~
return true;
}
}
}
// 处理成功,让父类进行接收下个包
return false;
}
}
ByteArrayCodecFactory.java
package org.bruce.mina.cpp.codec; import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder; /**
* @author BruceYang
* 字节数组编解码工厂
*/
public class ByteArrayCodecFactory implements ProtocolCodecFactory { private ByteArrayDecoder decoder;
private ByteArrayEncoder encoder; public ByteArrayCodecFactory() {
encoder = new ByteArrayEncoder();
decoder = new ByteArrayDecoder();
} @Override
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
} @Override
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
} }
NumberUtil.java
package org.bruce.mina.cpp.util; /**
* @author yang3wei
* int、byte[] 相互转换的工具类~
*/
public class NumberUtil { /**
* 将整型转换为字节数组~
* @param integer
* @return
*/
public static byte[] int2bytes(int integer) {
byte[] bytes = new byte[4];
bytes[0] = (byte) (integer & 0xff); // 最低位
bytes[1] = (byte) ((integer >> 8) & 0xff); // 次低位
bytes[2] = (byte) ((integer >> 16) & 0xff); // 次高位
bytes[3] = (byte) (integer >>> 24); // 最高位,无符号右移。
return bytes;
} /**
* 将字节数组转换为整型~
* @param bytes
* @return
*/
public static int bytes2int(byte[] bytes) {
// 一个 byte 数据左移 24 位变成 0x??000000,再右移 8 位变成 0x00??0000(| 表示按位或)
int integer = (bytes[0] & 0xff)
| ((bytes[1] << 8) & 0xff00)
| ((bytes[2] << 24) >>> 8)
| (bytes[3] << 24);
return integer;
}
}
mina 字节数组编解码器的写法 II的更多相关文章
- mina 字节数组编解码器的写法 I
mina 服务器与 mina 客户端通讯的话, 一.传递 String 时编解码工厂使用 mina 自带的 TextLineCodecFactory 即可: 二.传递 java 对象或 byte[] ...
- 使用 mina 传输大字节数组
转载自:http://seara520.blog.163.com/blog/static/16812769820103214817781/ 使用mina传输超过2k以上的数据时(采用tcp方式,如果是 ...
- Java将文件转为字节数组
Java将文件转为字节数组 关键字:文件,文件流,字节流,字节数组,二进制 摘要:最近工作中碰到的需求是,利用http传输二进制数据到服务器对应接口,需要传输userId, file(加密后)等一系列 ...
- (IEEE-754) 字节数组与浮点数之间的互相转换(MODBUS float类型)
在做上位机开发过程中,经常会碰到字节数组与浮点数,整数等数据之间的转换,有时为了验证数据是否解析正确,得借助于IEEE浮点数工具,本文把基于c#实现的浮点数与字节数组(或16进制的字符串)转换的实现方 ...
- C#字节数组转换成字符串
C#字节数组转换成字符串 如果还想从 System.String 类中找到方法进行字符串和字节数组之间的转换,恐怕你会失望了.为了进行这样的转换,我们不得不借助另一个类:System.Text.Enc ...
- 【.net】从比较两个字节数组谈起
上午,有位初学者朋友问:如何比较两个字节数组中各字节是否相等? 不许笑,我一向反对嘲笑初学者,初学者不认真学习时你可以批评,但不能讥嘲.你不妨想想,你自己开始学习编程的时候又是什么个光景? 好,于是, ...
- 使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转
包名称:org.apache.commons.codec.binary 类名称:org.apache.commons.codec.binary.Hex 1.字节数组(byte[])转为十六进制(Hex ...
- java 字节数组转int
4字节数组转int类型 小端模式 /** * 数组转int类型 * * @param src * @return */ public static int bytesToInt(byte[] src) ...
- java 读取文件的字节数组
/*文件64位编码*/ public static void main(String[] args) { byte[] fileByte = toByteArray(newFile); St ...
随机推荐
- Windows下Mysql5.6启用监控执行脚本的日志
修改my.ini (我的MySQL安装位置是:E:\MySQL\MySQL Server 5.6) log-output=FILE general-log=1 general_log_file=&qu ...
- CCF 201312-5 I’m stuck! (暴力,BFS)
问题描述 给定一个R行C列的地图,地图的每一个方格可能是'#', '+', '-', '|', '.', 'S', 'T'七个字符中的一个,分别表示如下意思: '#': 任何时候玩家都不能移动到此方格 ...
- C++中使用接口
面向对象的语言诸如JAVA提供了Interface来实现接口,但C++却没有这样一个东西,尽管C++ 通过纯虚基类实现接口,譬如COM的C++实现就是通过纯虚基类实现的(当然MFC的COM实现用了嵌套 ...
- 我对CONTAINING_RECORD宏的详细解释
宏CONTAINING_RECORD的用处其实还是相当大的, 而且很是方便, 它的主要作用是: 根据结构体中的某成员的指针来推算出该结构体的指针! 下面从一个简单的例子开始说起: 我们定义一个结构体, ...
- zendstudio 出现failed to create the java machine转
是因为配置java虚拟机内存太小 打开zend for eclipse 10.5时报了个错: failed to create the java virtual machine google了一下,解 ...
- socket的异步回调函数,采用一问一答
socket.Send(buf); AsyncCallback callback = new AsyncCallback(ReceiveData5); mysocket.BeginReceive(Wi ...
- GIT 中提示 please tell me who you are
如果使用git过程中出现了,please tell me who you are ,需要设置一下使用者的身份. 1.git config user.name "username" ...
- Java利用Math.random()方法随机生成A-Z的字符
package reverse; import java.text.DecimalFormat; public class Reverse { public static void main(Stri ...
- C++学习笔记之友元
一.引言 C++控制对类对象私有部分(private)的访问,通常只能通过公有的(public)类方法去访问.但是有时候这种限制太严格,不适合特定的问题,于是C++提供了另外一种形式的访问权限:友元. ...
- linux C(hello world)程序调试
程序的调试(先得安装gdb工具,以root身份执行命令:sudo apt-get install gdb) 程序的调试是一个很重要的环节,windows IDE下那些强大的调试功能,Linux以什么来 ...