发送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;
}

原文地址:https://www.cnblogs.com/yizw/p/8041948.html