问题,前段时间碰到一个socket获取不到报文的情况,正常的socket获取不到报文,后来尝试下available方法
参考:
https://www.aliyun.com/jiaocheng/774451.html
http://jiangzhengjun.iteye.com/blog/509900
https://blog.csdn.net/wj1900/article/details/5290861
public static byte[] sendMessageByAvail(String url, int port, byte[] request, int timeout) throws ConnectException {
byte[] res = null;
Socket socket = null;
InputStream is = null;
OutputStream os = null;
try {
socket = new Socket(url, port);
socket.setSoTimeout(timeout);
os = socket.getOutputStream();
os.write(request);
os.flush();
is = socket.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
do {
count = is.read(buffer);
if (count != -1) {
bos.write(buffer, 0, count);
}
} while (is.available() != 0);
res = bos.toByteArray();
os.close();
is.close();
socket.close();
} catch (ConnectException e1) {
log.info("连接主机失败:", e1);
throw e1;
} catch (Exception e) {
log.info("请求异常:", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return res;
}