zoukankan      html  css  js  c++  java
  • 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>
    " + 
                            "<name>张山</name>
    " + 
                            "<amt>100000</amt>
    " + 
                            "<time>20171011091230</time>
    " + 
                            "<type>支出</type>
    " + 
                            "<opt>信用卡还款</opt>
    " + 
                            "<phone>18940916007</phone>
    " + 
                            "</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";

     
  • 相关阅读:
    asp 向另一个页面传递数组
    TSQL Program Rule and Tips 规则与优化
    虚函数 纯虚函数 抽象类
    static (c#)
    简单游标
    抽象方法 抽象类 (abstract)
    清理电脑
    泛型学习
    继承(对象生命周期) + 覆盖[new](索引函数) + 重载[virtual/override]
    #干货向#jQuery性能优化指南
  • 原文地址:https://www.cnblogs.com/startnow/p/7676521.html
Copyright © 2011-2022 走看看