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

     
  • 相关阅读:
    P1199三国游戏(博弈论)
    平方求和
    完全立方公式
    P1414 又是毕业季(数论)
    P1514 引水入城(搜索+线段完全覆盖)
    树莓派利用Django搭建聊天网页服务器 —— 准备篇
    树莓派下安装Django环境
    Linux终端光标消失问题
    OpenCV 简介
    树莓派是什么?能干什么?和单片机有什么区别?
  • 原文地址:https://www.cnblogs.com/startnow/p/7676521.html
Copyright © 2011-2022 走看看