今天自己實現了下TCP處理粘包的問題

用的是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);
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章