阅读更多
用的是netty 的TCP服务框架 具体代码实现
package com.tongfang.forward.server.handler;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class MyTcpHandler extends ChannelHandlerAdapter {
static int count = 1;
byte[] bigdata=new byte[0];
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
ByteBuf data = (ByteBuf) msg;
int bytes = data.readableBytes();
byte[] temp = new byte[bytes];
data.readBytes(temp);
//将读取到的字节保存
bigdata = combineByteArray(bigdata,temp);
//如果不满足协议最少4个字节的话就不处理
if(bigdata.length< 4){
System.out.println("不满足协议要求最少4个字节");
return;
}
//我这边定义的协议头是4个字节
byte[] lengByte = new byte[4];
System.arraycopy(bigdata, 0, lengByte, 0, 4);
//获取内容长度
int length = bytesToInt(lengByte);
System.out.println("协议长度为:"+length);
if(length > bigdata.length){
System.out.println("不满足协议长度要求要求");
return;
}
//判断获取到的数据能解析出来几个
int j = bigdata.length%(length+4)>0?bigdata.length/(length+4)-1:bigdata.length/(length+4);
for(int i= 0; i < j; i++){
byte[] head = new byte[4];
//获取长度
System.arraycopy(bigdata, 0, head, 0, 4);
int tempLength = bytesToInt(head);
byte[] temp2 = new byte[tempLength];
//获取内容
System.arraycopy(bigdata, 4, temp2, 0, tempLength);
String body = new String(temp2, "UTF-8");
export(body,count);
//去掉内容
bigdata = copyNewAry(bigdata,tempLength+4,bigdata.length-tempLength-4);
count++;
}
}
}
public void export(String str,int count){
FileWriter fw = null;
try {
File f=new File("E:\\data"+count+".txt");
if(!f.exists()){
f.createNewFile();
}
fw = new FileWriter(f, true);
PrintWriter pw = new PrintWriter(fw);
pw.println(str);
pw.flush();
fw.flush();
pw.close();
fw.close();
System.out.println("写入完成···");
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] copyNewAry(byte[] array,int start,int length){
byte[] newAry = new byte[length];
System.arraycopy(array, start, newAry, 0, newAry.length);
return newAry;
}
private static byte[] combineByteArray(byte[] array1, byte[] array2) {
byte[] combined = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, combined, 0, array1.length);
System.arraycopy(array2, 0, combined, array1.length, array2.length);
return combined;
}
public int bytesToInt(byte[] bArr) {
if(bArr.length!=4){
return -1;
}
return (int) ((((bArr[0] & 0xff) << 24)
| ((bArr[1] & 0xff) << 16)
| ((bArr[2] & 0xff) << 8)
| ((bArr[3] & 0xff) << 0)));
}
public static void main(String[] args) {
System.out.println(1024%252);
}
}