/**
* 十六进制字符串转字节数组
* @param src
* @return
*/
public static byte[] hexString2Bytes(String src) {
int l = src.length() / 2;
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
ret[i] = (byte) Integer
.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
}
return ret;
}
public Socket init() {
Socket socket = new Socket(ip, port);
socket.setKeepAlive(true);
//超时时间2秒
socket.setSoTimeout(2000);
logger.info("socket连接建立:ip{},port:{},status:{}", ip, port, socket.isConnected());
return socket ;
}
/**
* decription 发送并接收指令响应
*
* @author wangjingjing
* @date 2020/9/30 17:05
*/
public static String sendAndReceive(String cmd, Socket socket) {
//socket连接建立
String res = null;
try {
sendCmd(cmd, socket);
res = readRes(socket);
logger.info(cmd.replace("\r\n", "") + "指令响应信息:" + res);
if (!StringUtils.isEmpty(res)) {
res = res.replace("\r\n", "");
}
} catch (Exception e) {
logger.error("系统异常,", e);
}
return res;
}
/**
* decription 发送指令
*
* @author wangjingjing
* @date 2020/9/29 17:18
*/
public static void sendCmd(String cmd, Socket socket) {
try {
socket.getOutputStream().write(hexString2Bytes(cmd));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* decription 接收响应数据 (建议根据实际场景使用下面的接收数据方案)
*
* @author wangjingjing
* @date 2020/9/29 17:18
*/
public static String readRes(Socket socket) {
// 从服务端程序接收数据
String result = "";
InputStream in = null;
try {
in = socket.getInputStream();
while (in.available() != 0) {
byte b = (byte) in.read();
String hex = "";
hex = String.valueOf(HEXSTR.charAt((b & 0xF0) >> 4));
hex += String.valueOf(HEXSTR.charAt(b & 0x0F));
result += hex;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
上面的可能会有问题,因为available()可能会因为服务端分批次发送获取数据不全,可结合具体业务按下面的操作
//根据实际业务接收数据
private static final String END_SYMBOL = "040E2END"; //数据发送结束标识符
public static String readRes(Socket socket) {
// 从服务端程序接收数据
String result = "";
try {
InputStream in = socket.getInputStream();
int i;
while ((i = in.read()) != -1) {
byte b = (byte) i;
String hex = "";
hex = String.valueOf(HEXSTR.charAt((b & 0xF0) >> 4));
hex += String.valueOf(HEXSTR.charAt(b & 0x0F));
result += hex;
if (result.endsWith(END_SYMBOL) || result.endsWith(SUCCESS_RES)) {
return result; //关键返回
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}