定長消息報文的組包與解包簡單封裝(Java實現(xiàn))

報文 組包 解包

  • 在實際項目中經(jīng)常會碰到不同系統(tǒng)之間的數(shù)據(jù)交換祥楣,有些是用webservice订雾。有些則是使用發(fā)socket消息的方式慈省,將需要發(fā)送的消息組裝成特定格式的字符串或Xml格式的文件憔维,再通過socket編程發(fā)送到對方系統(tǒng)炬守。本文主要討論組裝成定長字符串牧嫉。
  • 抽象任何一個定長消息包(MsgPackage)都是由一個或多個消息片(MsgPiece)組成。任何一個消息片都是由一個或多個消息域(MsgField)組成减途。消息域的屬性有:域名酣藻、長度、值鳍置、如果值的長度小于定義的最大長度那值是靠左還是右對齊其余的是用什么字符填充辽剧。

工具代碼

消息域類

package socket.msg;

/**
 * 消息域
 * @author Zhenwei.Zhang (2013-9-25)
 */
public class MsgField {
    
    public MsgField (String name, int length, char fillChar, FillSide fillSide) {
        this.name = name;
        this.length = length;
        this.fillChar = fillChar;
        this.fillSide = fillSide;
    }
    
    /**
     * 填充位置
     * @author Zhenwei.Zhang (2013-9-25)
     */
    public enum FillSide {
        LEFT, RIGHT
    }

    /** 域名稱 */
    private String name;
    /** 長度 */
    private int length;
    /** 填充字符 */
    private char fillChar;
    /** 填充位置 */
    private FillSide fillSide;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public char getFillChar() {
        return fillChar;
    }

    public void setFillChar(char fillChar) {
        this.fillChar = fillChar;
    }

    public FillSide getFillSide() {
        return fillSide;
    }

    public void setFillSide(FillSide fillSide) {
        this.fillSide = fillSide;
    }

}

報文消息片類

package socket.msg;

import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import socket.msg.MsgField.FillSide;

/**
 * 消息片,由多個消息域按一定的順序組成
 * @author Zhenwei.Zhang (2013-9-25)
 */
public abstract class MsgPiece {
    
    /** 消息域列表 */
    private List<MsgField> itemList = new LinkedList<MsgField>();
    
    public MsgPiece(MsgField[] items) {
        itemList = new LinkedList<MsgField>();
        for (int i = 0; i < items.length; i++) {
            itemList.add(items[i]);
        }
    }
    
    /**
     * 組消息
     * @author Zhenwei.Zhang (2013-9-25)
     * @param charsetName
     * @return
     * @throws Exception
     */
    public byte[] pack(String charsetName) throws Exception {
        StringBuffer result = new StringBuffer();
        byte[] b = null;
        try {
            for (MsgField item : itemList) {
                PropertyDescriptor pd = new PropertyDescriptor(item.getName(), this.getClass());
                Method readMethod = pd.getReadMethod();
                Object gotVal = readMethod.invoke(this);
                String strFill = gotVal == null ? "" : gotVal.toString();
                result.append(this.autoFill(strFill, item.getFillChar(), item.getFillSide(), item.getLength(), charsetName));
            }
            b = result.toString().getBytes(charsetName);
        } catch (Exception e) {
            throw new Exception("組消息出錯:" + e.getMessage(), e);
        }
        
        return b;
    }
    
    /**
     * 解消息
     * @author Zhenwei.Zhang (2013-9-25)
     * @param msg
     * @param charsetName
     * @throws Exception
     */
    public void unPack(byte[] msg, String charsetName) throws Exception {
        if (msg.length != this.getLength()) {
            throw new Exception("解消息出錯税产,消息長度不合法怕轿!");
        }
        
        int index = 0;
        try {
            for (MsgField item : itemList) {
                String value = new String(msg, index, item.getLength(), charsetName);
                value = this.getRealVal(value, item.getFillSide(), item.getFillChar());
                
                PropertyDescriptor pd = new PropertyDescriptor(item.getName(), this.getClass());
                Method setMethod = pd.getWriteMethod();
                if (pd.getPropertyType().equals(byte.class) || pd.getPropertyType().equals(Byte.class)) {
                    setMethod.invoke(this, Byte.parseByte(value));
                }else if (pd.getPropertyType().equals(short.class) || pd.getPropertyType().equals(Short.class)) {
                    setMethod.invoke(this, Short.parseShort(value));
                }else if (pd.getPropertyType().equals(int.class) || pd.getPropertyType().equals(Integer.class)) {
                    setMethod.invoke(this, Integer.parseInt(value));
                }else if (pd.getPropertyType().equals(long.class) || pd.getPropertyType().equals(Long.class)) {
                    setMethod.invoke(this, Long.parseLong(value));
                }else if (pd.getPropertyType().equals(float.class) || pd.getPropertyType().equals(Float.class)) {
                    setMethod.invoke(this, Float.parseFloat(value));
                }else if (pd.getPropertyType().equals(double.class) || pd.getPropertyType().equals(Double.class)) {
                    setMethod.invoke(this, Double.parseDouble(value));
                }else if (pd.getPropertyType().equals(char.class) || pd.getPropertyType().equals(Character.class)) {
                    setMethod.invoke(this, value.toCharArray()[0]);
                }else if (pd.getPropertyType().equals(boolean.class) || pd.getPropertyType().equals(Boolean.class)) {
                    setMethod.invoke(this, Boolean.valueOf(value));
                }else {
                    setMethod.invoke(this, value);
                }
                index += item.getLength();
            }
        } catch (Exception e) {
            throw new Exception("解消息出錯:" + e.getMessage(), e);
        }
    }
    
    /**
     * 獲得消息片長
     * @author Zhenwei.Zhang (2013-9-25)
     * @return
     */
    public int getLength() {
        int length = 0;
        for (MsgField item : itemList) {
            length += item.getLength();
        }
        return length;
    }
    
    /**
     * 格式化真實值為指定長度字符串,超長自動截取
     * @author Zhenwei.Zhang (2013-9-26)
     * @param value
     * @param fillChar 填充字符
     * @param side 填充位置
     * @param totalLen 域定義的長度
     * @param charsetName 編碼
     * @return
     */
    private String autoFill(String value, char fillChar, FillSide side, int totalLen, String charsetName) {
        try {
            if (value == null) {
                value = "";
            }
            StringBuffer sbuffBuffer = new StringBuffer();
            // 長度超過指定長度辟拷,截取
            if (value.getBytes(charsetName).length > totalLen) {
                byte[] data = new byte[totalLen];
                System.arraycopy(value.getBytes(charsetName), 0, data, 0, totalLen);
                sbuffBuffer.append(new String(data, charsetName));
                return sbuffBuffer.toString();
            }
            if (side == socket.msg.MsgField.FillSide.RIGHT) {
                sbuffBuffer.append(value);
            }
            for (int i = value.getBytes(charsetName).length; i < totalLen; i++) {
                sbuffBuffer.append(fillChar);
            }
            if (side == socket.msg.MsgField.FillSide.LEFT) {
                sbuffBuffer.append(value);
            }
            return sbuffBuffer.toString();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("系統(tǒng)不支持" + charsetName + "編碼");
        }
    }
    
    /**
     * 獲得消息域的真實值
     * @author Zhenwei.Zhang (2013-9-26)
     * @param value
     * @param side 填充位置
     * @param fillChar 填充字符
     * @return
     * @throws Exception
     */
    private String getRealVal(String value, FillSide side, char fillChar) throws Exception {
        char[] chars = value.toCharArray();
        if (FillSide.LEFT == side) {
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (fillChar == chars[i]) {
                    index ++;
                } else {
                    continue;
                }
            }
            return value.substring(index);
        } else if (FillSide.RIGHT == side) {
            int index = chars.length - 1;
            for (int i = index; i >= 0; i--) {
                if (fillChar == chars[i]) {
                    index --;
                } else {
                    continue;
                }
            }
            return value.substring(0, index + 1);
        } else {
            throw new Exception("無效的填充位置");
        }
    }

}

消息包類

package socket.msg;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * 消息包撞羽,由多個消息片組成
 * @author Zhenwei.Zhang (2013-10-12)
 */
public abstract class MsgPackage {
    
    /** 消息包的消息片數(shù)組 */
    String[] pieces = null;
    
    public MsgPackage(String... pieName) {
        pieces = pieName;
    }
    
    /**
     * 組包
     * @author Zhenwei.Zhang (2013-9-26)
     * @param charsetName
     * @return
     * @throws Exception
     */
    public byte[] pack(String charsetName) throws Exception {
        int index = 0;
        byte[] result = new byte[this.getLength()];
        for (String p : pieces) {
            PropertyDescriptor pd = new PropertyDescriptor(p, this.getClass());
            Method getterMethod = pd.getReadMethod();
            MsgPiece piece = (MsgPiece)getterMethod.invoke(this);
            if (piece == null) { //屬性為空則該屬性組空串
                piece = (MsgPiece) pd.getPropertyType().newInstance();
            }
            byte[] t = piece.pack(charsetName);
            System.arraycopy(t, 0, result, index, t.length);
            index += t.length;
        }
        return result;
    }
    
    /**
     * 解包
     * @author Zhenwei.Zhang (2013-9-26)
     * @param msg
     * @param charsetName
     * @throws Exception
     */
    public void unPack(byte[] msg, String charsetName) throws Exception {
        if (msg.length != this.getLength()) {
            throw new Exception("解消息出錯,消息包長度不合法衫冻!");
        }

        int index = 0;
        for (String p : pieces) { // 創(chuàng)建一個新的屬性對象诀紊,解包,賦值
            PropertyDescriptor pd = new PropertyDescriptor(p, this.getClass());
            Method writeMethod = pd.getWriteMethod();
            MsgPiece piece = (MsgPiece) pd.getPropertyType().newInstance();
            byte[] t = new byte[piece.getLength()];
            System.arraycopy(msg, index, t, 0, t.length);
            piece.unPack(t, charsetName);
            writeMethod.invoke(this, piece);
            index += t.length;
        }
    }
    
    /**
     * 獲得消息包長度
     * @author Zhenwei.Zhang (2013-9-26)
     * @return
     * @throws Exception
     */
    public int getLength() throws Exception {
        int length = 0;
        try {
            for (String p : pieces) {
                PropertyDescriptor pd = new PropertyDescriptor(p, this.getClass());
                Method getterMethod = pd.getReadMethod();
                MsgPiece piece = (MsgPiece)getterMethod.invoke(this);
                if (piece == null) {
                    piece = (MsgPiece) pd.getPropertyType().newInstance();
                }
                length += piece.getLength();
            }
        } catch (Exception e) {
            throw new Exception("獲得消息包長度錯誤:" + e.getMessage(), e);
        }
        return length;
    }
}

實例

以下是使用上述封裝做的簡單實現(xiàn)例子:
定義一個消息由消息頭和消息體組成隅俘,消息頭由name,sex,UAge,amt等屬性組成邻奠,消息體由content屬性組成到推。

package socket.msg.test;

import socket.msg.MsgField;
import socket.msg.MsgPiece;
import socket.msg.MsgField.FillSide;

public class TestHead extends MsgPiece {
    
    private String name;
    private boolean sex;
    private int UAge;
    private String URL;
    private double amt;

    public int getUAge() {
        return UAge;
    }

    public void setUAge(int uAge) {
        UAge = uAge;
    }
    
    public double getAmt() {
        return amt;
    }

    public void setAmt(double amt) {
        this.amt = amt;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    public String getURL() {
        return URL;
    }

    public void setURL(String uRL) {
        URL = uRL;
    }

    private static final MsgField[] items = new MsgField[]{
            new MsgField("name", 10, ' ', FillSide.RIGHT),
            new MsgField("sex", 10, '0', FillSide.LEFT),
            new MsgField("UAge", 10, '0', FillSide.LEFT),
            new MsgField("URL", 10, ' ', FillSide.RIGHT),
            new MsgField("amt", 10, '0', FillSide.LEFT)
        };
    
    public TestHead() {
        super(items);
    }
}
package socket.msg.test;

import socket.msg.MsgField;
import socket.msg.MsgPiece;
import socket.msg.MsgField.FillSide;

public class TestBody extends MsgPiece {
    
    private static final MsgField[] items = new MsgField[]{
        new MsgField("content", 20, ' ',FillSide.RIGHT),
    };
    
    public TestBody() {
        super(items);
    }
    
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
package socket.msg.test;

import socket.msg.MsgPackage;

public class TestPackage extends MsgPackage {
    
    public TestPackage() {
        super("t1", "t2");
    }
    
    private TestHead t1;
    
    private TestBody t2;

    public TestHead getT1() {
        return t1;
    }

    public void setT1(TestHead t1) {
        this.t1 = t1;
    }

    public TestBody getT2() {
        return t2;
    }

    public void setT2(TestBody t2) {
        this.t2 = t2;
    }

}

測試

package socket.msg.test;

import java.io.UnsupportedEncodingException;

public class Test {

    /**
     * @author Zhenwei.Zhang (2013-11-12)
     * @param args
     * @throws Exception 
     * @throws UnsupportedEncodingException 
     */
    public static void main(String[] args) throws UnsupportedEncodingException, Exception {
        TestHead head = new  TestHead();
        head.setName("name");
        head.setAmt(12.121);
        head.setSex(false);
        head.setURL("http://asdsaaaaaaaaaaaaaaaaaaaaaaa");
        head.setUAge(111);
        
        TestBody body = new TestBody();
        body.setContent("content");
        
        TestPackage packagee = new TestPackage();
        packagee.setT1(head);
        packagee.setT2(body);
        
        System.out.println(new String(packagee.pack("GBK"), "GBK"));
        
        TestPackage packagee2 = new TestPackage();
        String str = "name      000000true0000000111http://asd000012.121content             ";
        packagee2.unPack(str.getBytes("GBK"), "GBK");
        System.out.println(packagee2.getT1().isSex());
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市惕澎,隨后出現(xiàn)的幾起案子莉测,更是在濱河造成了極大的恐慌,老刑警劉巖唧喉,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捣卤,死亡現(xiàn)場離奇詭異,居然都是意外死亡八孝,警方通過查閱死者的電腦和手機董朝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來干跛,“玉大人子姜,你說我怎么就攤上這事÷ト耄” “怎么了哥捕?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長嘉熊。 經(jīng)常有香客問我遥赚,道長,這世上最難降的妖魔是什么阐肤? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任凫佛,我火速辦了婚禮,結(jié)果婚禮上孕惜,老公的妹妹穿的比我還像新娘愧薛。我一直安慰自己,他們只是感情好衫画,可當(dāng)我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布毫炉。 她就那樣靜靜地躺著,像睡著了一般碧磅。 火紅的嫁衣襯著肌膚如雪碘箍。 梳的紋絲不亂的頭發(fā)上遵馆,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天鲸郊,我揣著相機與錄音,去河邊找鬼货邓。 笑死秆撮,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的换况。 我是一名探鬼主播职辨,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼盗蟆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了舒裤?” 一聲冷哼從身側(cè)響起喳资,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎腾供,沒想到半個月后仆邓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡伴鳖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年节值,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片榜聂。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡搞疗,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出须肆,到底是詐尸還是另有隱情匿乃,我是刑警寧澤,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布豌汇,位于F島的核電站扳埂,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏瘤礁。R本人自食惡果不足惜阳懂,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望柜思。 院中可真熱鬧岩调,春花似錦、人聲如沸赡盘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽陨享。三九已至葱淳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間抛姑,已是汗流浹背赞厕。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留定硝,地道東北人皿桑。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親诲侮。 傳聞我的和親對象是個殘疾皇子镀虐,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容