java socket發送xml報文


ServerRun.java

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRun { public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(3456); System.out.println("-----正在監聽3456端口---"); Socket socket = server.accept(); InputStream is = socket.getInputStream(); // 前8個字節 byte[] b = new byte[8]; is.read(b); int len = Integer.parseInt(new String(b, "UTF-8")); // 用來填充xml b = new byte[len]; is.read(b); // 關閉資源 is.close(); socket.close(); server.close(); String result = new String(b, "UTF-8"); System.out.println(result); } }

ClientRun.java

import java.io.OutputStream;
import java.net.Socket;

public class ClientRun {

    public static void main(String[] args) throws Exception {
        String xml = "<xml>\r\n" + 
                        "<name>張山</name>\r\n" + 
                        "<amt>100000</amt>\r\n" + 
                        "<time>20171011091230</time>\r\n" + 
                        "<type>支出</type>\r\n" + 
                        "<opt>信用卡還款</opt>\r\n" + 
                        "<phone>18940916007</phone>\r\n" + 
                        "</xml>";
        Socket client = new Socket("127.0.0.1", 3456);
        OutputStream out = client.getOutputStream();

        byte[] b = xml.getBytes("UTF-8");

        out.write(int2Bytes8(b.length));
        out.write(b);
        out.close();
        client.close();
    }

    /**
     * @Title: int2Bytes8   
     * @Description: 數字[2] 變成八個字節的 ['0' '0' '0' '0' '0' '0' '0' '2']   
     * @param: @param num
     * @param: @return      
     * @return: byte[]      
     */
    public static byte[] int2Bytes8(int num) {
        StringBuffer sb = new StringBuffer(String.valueOf(num));
        int length = 8 - sb.length();
        for (int i = 0; i < length; i++) {
            sb.insert(0, '0');
        }
        return sb.toString().getBytes();
    }
}

注:代碼中字符串的拼接

是eclipse自動完成的,我只是從wps ( 其他文本編輯器也可以)里面復制到

String str="copy here";

 


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM