转载自:http://seara520.blog.163.com/blog/static/16812769820103214817781/
使用mina传输超过2k以上的数据时(采用tcp方式,如果是UDP方式,好像一次传输的数据不能超过256字节,如果超过mina不会分批次发送,而tcp方式会分批次发送),mina会自动将这些数据分成多次发送。由于是分批次发送数据,所有客服端在接受数据时,需要等所有的数据接受完之后才能解码,否则无法解码,或者只能读取到部分文件。
以下是一个发送、接受大字节数组的主要代码
服务端向客服端发送字节数组
服务端代码:
编码器:
public class ImageDataEncoder extends ProtocolEncoderAdapter { @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { CharsetEncoder charset = Charset.forName("UTF-8").newEncoder(); ImageData image = (ImageData) message; IoBuffer buffer = IoBuffer.allocate(2048).setAutoExpand(true); buffer.putString(image.getYh(), charset);// 发送数据类型 buffer.putInt(image.getLength());// 发送字节数组的总长度,共解码时使用 buffer.put(image.getBimage());// 发送字节数据 buffer.flip(); out.write(buffer); buffer.free(); }}
ImageData.java
package org.bruce.mina.cpp.client;public class ImageData { private static final long serialVersionUID = 1L; private String yh = YHConstants.YH_IMG;// 数据类型 public int length = 0;// 字节数组长度 private byte[] bimage;// 待发送的字节数组 private BufferedImage image;