public String getSocketClient(String ip, int port,String order,int num){ try { if(5 > num){ // 和服务器创建连接 Socket socket = SocketTcpClientUtil.getConnection(ip, port); if(socket == null){ logger.error("获取socket失败"); return null; } // 要发送给服务器的信息 OutputStream os = socket.getOutputStream(); os.write(hexStrToByteArrs(order)); Thread.sleep( 1000);//等待1秒 socket.shutdownOutput(); // 从服务器接收的信息 InputStream is = socket.getInputStream(); byte b[] = new byte[1024]; int len = is.read(b); if (len > 0) { // 收到服务器发送的信息 logger.info("收到服务器发送的信息!"); } else { //没收到服务器发送的信息 logger.info("没收到服务器发送的信息!"); //没收到重新发送 throw new Exception("没收到服务器发送的信息"); } //接收的字节转16进制 String result = bytesToHexString(b); //截取重量信息 String substring = result.substring(10, 14); //16进制转10进制 int convert = Integer.parseInt(substring, 16); //最终结果 double weight = convert * 0.001; //保留3位小数 String str = String.format("%.3f",weight); is.close(); os.close(); socket.close(); return str; } return null; } catch (Exception e) { logger.error("执行失败,网络超时"); e.printStackTrace(); String weight = null; try { num++; logger.info("正在重新发送,第" + num + "次"); weight = getSocketClient(ip, port, order, num); } catch (Exception ea) { logger.info("重新执行失败,网络超时!"); ea.printStackTrace(); } return weight; } }
电子秤TCP连接获取重量,包括没获取成功重新获取
最新推荐文章于 2024-09-13 21:15:00 发布