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";

 


 

 
posted @ 2017-10-16 13:07  一支小白  阅读(17753)  评论(0编辑  收藏  举报