Socket客户端通用代码

这段Java代码展示了如何创建一个通用的Socket客户端,用于连接指定IP和端口,发送UTF-8编码的XML报文,并接收响应。报文头包含字节长度信息,通过字节流进行传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中一直使用的就是这部分源码。字符集是utf-8,xml报文格式,需要在报文头拼上字节长度。传输方式是字节流。发出来,与大家共勉。

public static Map queryESB(String xml) throws Exception {
        
        StringBuilder errorMsg = new StringBuilder();

        Map bodymap = new HashMap();

        Map<String, String> proMap = PropertiesUtil.buildproperties();

        String ip = proMap.get("ip");
        int port = Integer.parseInt(proMap.get("port"));

        String responseMessage = "";
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
            socket.setSoTimeout(60 * 1000);
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            out.write(xml.getBytes("UTF-8"));
            out.flush();
            byte[] header = new byte[8];
            int headerLength = in.read(header);
            String charset = "UTF-8";
            String headerInfo = "";
            int length = 0;
            byte[] body;
            if (headerLength != 8) {
                errorMsg.append("报文长度字节不足8位!"+headerLength);
            } else {
                headerInfo = new String(header, charset);
                length = Integer.parseInt(headerInfo.trim());
                body = new byte[length];
                int off = 0;
                while (true) {
                    int ret = in.read(body, off, body.length - off);
                    if (ret <= 0) {
                        break;
                    }
                    off += ret;
                }
                responseMessage = new String(body, charset);
                
                System.out.println("返回报文:"+responseMessage);
            }

        } catch (Exception e) {
            errorMsg.append("发送失败!"+e);
            System.out.println("ESB request is fail");
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                errorMsg.append("客户端关闭socket异常!");
            }
        }
        if (errorMsg.length() == 0) {
            bodymap = resolveXML(errorMsg, responseMessage);
        }

        return bodymap;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值