javaSE字符串

很多场景的编程都是回归到最基本的基础应用:字节数组输入流ByteArrayInputStream的应用

样例:
    00000154***********(某协议传输的内容1)00012323*******************(某协议传输的内容2) … 00000859******(某协议传输的内容3)
   
其中,连续8byte的数字代表业务信息协议内容的长度,后边“******”即为某协议传输的消息内容(UTF-8编码)
说明:
    此处8byte意为连续8个字符,每个字符内存储一个数字,连续8个字符共同代表一个数字

按照样例进行通信传输,到接收方只要解出对应的协议内容部分。

方法一:

public static List<String> readMessage(String message) throws Exception {
        List<String> list = new ArrayList<String>();
       
        while ( true ) {
            if(message == null || message.equals("")) {
                break;
            }
            String strLen = message.substring(0, 8);
            int len = Integer.parseInt(strLen);
            list.add(message.substring(8, 7+1+len));
            message = message.substring(8+len);
           
        }
        return list;
    }

方法二:

public static List<String> readMessage(byte[] all) throws Exception {
        List<String> list = new ArrayList<String>();
        ByteArrayInputStream input = new ByteArrayInputStream(all);
        byte[ ] b = new byte[8];
        while (true) {
            String temp = null;
            String msgString = null;
            if (input.read(b) == -1)
                break;
            temp = Utils.byteToString(b);
            if (temp == null)
                continue;
            int msglength = Integer.parseInt(temp.trim());
            byte[] tempb = new byte[msglength];
            if (input.read(tempb) == -1)
                break;
            if (tempb != null) {
                msgString = Utils.byteToString(tempb);
                if (!Utils.IsNullStr(msgString))
                    list.add(msgString);
            }
        }
        return list;
    }

猜你喜欢

转载自lintaozhou.iteye.com/blog/2370905
今日推荐