`
milk_36
  • 浏览: 118247 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Mina 中结合DataInputStream和DataOutputStream的使用

阅读更多

 

最近在研究Mina的连接和数据传输。在网上找到些查考后就开始做些例子,从简单的socket连接了解nio原理(现在也只是了解而已),和数据的传输。然后在上手Mina的操作,发现mina确实不错。

但是我发现mina中在没有使用filter的情况下messageReceived(IoSession session, Object message),

message的数据类型是org.apache.mina.common.ByteBuffer,但是现在被IoBuffer个替代了。

原因是:

1.It doesn't provide useful getters and putters such as fill, get/putString,

   and get/putAsciiInt() enough. 

2.It is difficult to write variable-length data due to its fixed capacity。

IoBuffer中提供了put和get能方便的对数据进行操作这个与DataInputStream和DataOutputStream很相似!

但是我对IoBuffer.putString(CharSequence, CharsetEncoder)的使用不是很了解,所以在对String类型的数据

进行操作的时候卡壳了。

到网上找了很久,我也没搞清楚putString的使用!

我想DataInputStream和DataOutputStream的操作是很方便的,为什么mina就不行?

后来就一点点的试验,果然可以!下面贴出两端代码!

(1)DataOutputStream 发送

ByteArrayOutputStream outputPacket = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(outputPacket);
dos.writeUTF(str);
dos.flush();
byte[] bb=outputPacket.toByteArray();
b.putShort(bb.length);
b.put(bb);
b.flip();
session.write(b);
 (2)DataInputStream 读取
IoBuffer buf = (IoBuffer) message;
short len = buf.getShort();
byte[] readByte = new byte[len];
buf.get(readByte);
ByteArrayInputStream bai = new ByteArrayInputStream(readByte);
DataInputStream dis = new DataInputStream(bai);
dis.readUTF();

 

 

 

分享到:
评论
1 楼 wst302 2009-12-10  
学习了了,我正在找相关的资料

相关推荐

Global site tag (gtag.js) - Google Analytics