赞
踩
public class SocketReceiveUtil { public static void main(String[] args) { for (int i = 0; i < 5; i++) { String rtfNumber = getRtfNumber(); System.out.println(rtfNumber); } } private static String getRtfNumber() { try { return getNumber(); } catch (Exception e) { System.out.println("获取数据超时"); return ""; } } public static String getNumber() throws Exception { ServerSocket server = new ServerSocket(8888); try { Socket client = server.accept(); client.setSoTimeout(1000); try { InputStream inputStream = client.getInputStream(); byte[] bytes = new byte[1025]; int readBytes = 0; int len = bytes.length; while (readBytes < len) { int read = inputStream.read(bytes, readBytes, len - readBytes); //判断是不是读到了数据流的末尾 ,防止出现死循环。 if (read == -1) break; readBytes += read; } String resultNum = byteArrayToHexString(bytes); return StringUtils.isNotBlank(resultNum) ? resultNum : ""; } finally { client.shutdownInput(); client.close(); } } finally { server.close(); } } private static String byteArrayToHexString(byte b[]) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) resultSb.append(byteToHexString(b[i])); return resultSb.toString(); } private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}; private static String byteToHexString(byte b) { int n = b; if (n < 0) n += 256; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。