zoukankan      html  css  js  c++  java
  • 发送socket请求

    /**
    * 发送socket请求
    * @param formatData 格式化后的请求数据
    * @return json格式的字符串
    */
    public static String sendMessage(String formatData,String token) {
    String tokenResult = null;
    JSONObject jo = new JSONObject();
    String result = null;
    byte[] data;
    try {
    data = formatData.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
    jo.put("code", "9999");
    jo.put("msg", "数据转换异常!");
    return jo.toString();
    }
    byte[] header;
    Socket socket = null;
    InputStream inStream = null;
    try {
    socket = SocketFactory.getDefault().createSocket(IP,Integer.parseInt(PORT));
    socket.setReceiveBufferSize(2048);
    socket.setSendBufferSize(2048);
    socket.setSoTimeout(20000);
    socket.setKeepAlive(false);
    socket.setTcpNoDelay(false);
    //发送
    socket.getOutputStream().write(data);
    socket.getOutputStream().flush();
    //读取服务器端数据
    inStream = socket.getInputStream();
    header = new byte[8];
    inStream.read(header);
    String head = new String(header);

    int bodyLength = Integer.parseInt(head);
    byte[] body = new byte[bodyLength];
    int readLen = 0;
    while(readLen < bodyLength) {
    readLen += inStream.read(body,readLen,bodyLength-readLen);
    }
    String bodyStr = new String(body,"utf-8");
    byte[] respByte = bodyStr.getBytes();
    byte[] respResult = new byte[bodyLength - 56];
    System.arraycopy(respByte, 56, respResult, 0, bodyLength - 56);
    String resultStr = new String(respResult);
    //判断是否需要解密
    if ((token.length() > 0 || StringUtils.isNotEmpty(token)) && !resultStr.contains("message")) {
    tokenResult = AESUtils.decryptAES(resultStr, token);//使用token解密
    }else{
    tokenResult = resultStr;
    }
    String xmlToJson = xml2json(tokenResult);//xml转json
    jo.put("code", "0000");
    jo.put("result", xmlToJson);
    result = jo.toString();
    } catch (Exception e) {
    logger.error("customer-Exception-by-yizw: " + e.getMessage());
    jo.put("code", "9999");
    jo.put("msg", "客户端异常!");
    return jo.toString();
    }finally {
    if(null != inStream){
    try {
    inStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    jo.put("code", "9999");
    jo.put("msg", "IO关闭异常!");
    return jo.toString();
    }
    }
    if (socket != null) {
    try {
    socket.close();
    } catch (IOException e) {
    socket = null;
    logger.error("socket-close-exception-by-yizw:" + e.getMessage());
    jo.clear();
    jo.put("code", "9999");
    jo.put("msg", "socket关闭异常!");
    return jo.toString();
    }
    }
    }
    return result;
    }

  • 相关阅读:
    Urlrewrite 配置信息写在另外的文件
    maven项目动态替换配置中的值
    搭建一个java博客
    那个不嫌弃你穷的姑娘,如果有一天真的离开了你,那只是因为,你把她弄哭了。
    常规工作流模型
    浅谈https(创建、传输、断开)
    日志相关杂
    主键生成
    自动化部署脚本(windows上传到linux)
    简述IO
  • 原文地址:https://www.cnblogs.com/yizw/p/8041948.html
Copyright © 2011-2022 走看看