项目中的数据请求,因为是交易平台,数据的实时性要求比较高,从之前的轮询请求获取数据要改成数据的推送.
用的Socket.io 框架 . 因为数据量比较大,如果直接传输会对带宽造成影响.后台把数据压缩后传输,在客户端接收到数据后,解压后展示.
服务端压缩代码如下:
public static void sendMessage(SocketIOClient client,String message){
DeflaterOutputStream gzip = null;
Deflater deflater = null;
if(client==null){
return;
}
try{
if(client.get("isBinary").equals("true")){
deflater = new Deflater(5, true);
ByteArrayOutputStream arrayOutputStream = tl.get();
if(arrayOutputStream==null){
arrayOutputStream = new ByteArrayOutputStream ();
tl.set(arrayOutputStream);
Logs.getinfoLogger().info("MsgThread ["+Thread.currentThread().getName()+"] init ByteArrayOutputStream");
}
arrayOutputStream.reset();
gzip = new DeflaterOutputStream(arrayOutputStream, deflater, 1024);
gzip.write(message.getBytes());
gzip.close();
byte[] bytes = arrayOutputStream.toByteArray();
client.sendEvent("m", bytes);
}else{
client.sendEvent("m", message);
}
}catch(Exception e){
try {
if(gzip!=null){
gzip.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Logs.getinfoLogger().info("MessageUtil-send error:",e);
}finally{
if(deflater!=null){
deflater.end();
}
}
}
刚开始解压数据总是乱码, 网上找了好多篇文章都没找到合适的解压办法,
最后发现是这句代码的原因 deflater = new Deflater(5, true); 加上了相对应的 Inflater decompresser = new Inflater(true);
成功解压, 解压代码如下:
/**
* 解压后台返回的数据
* @param bytes 后台返回的压缩后的数据
* @return
*/
private String decompress(byte[] bytes) {
Inflater decompresser = new Inflater(true);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InflaterInputStream iis = new InflaterInputStream(bais, decompresser);
byte[] buf = new byte[1024];
try {
int count = iis.read(buf);
while (count != -1) {
baos.write(buf, 0, count);
count = iis.read(buf);
}
return new String(baos.toByteArray());
} catch (final Exception e) {
e.printStackTrace();
return null;
} finally {
try {
iis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}