我们想要解除阻塞问题,就要从inputstream的异常做文章,因为socket的是否关闭会影响到inputstream是否产生异常;所以
int timeout=10000;
socket.setSoTimeout(timeout);
通过设置socket的链接接受数据最大延时时间;
在底层不发送数据时,我们则可以判定对方已经断开连接
socet会自动关闭;从而使read()函数进入异常状态;catch();
然后我们就可以在catch里面做文章结束线程释放内存;
具体代码如下
log.info("每3秒定时获取产品一线工位一的气密测试数据TCP数据(客户端)--oneAirtightTCPClient_1----start"); // 建立tcp服务 Socket socket = null; InputStream inputStream = null; try { // socket = new Socket(InetAddress.getLocalHost(), 8005); socket = new Socket("127.0.0.1", 8021); // 获取socket输出流对象 OutputStream outputStream = socket.getOutputStream(); // 写数据 String data = "pccommand:result1;"; outputStream.write(data.getBytes()); socket.setSoTimeout(10000); // 与服务器端交互 inputStream = socket.getInputStream(); }catch (Exception e) { e.printStackTrace(); } byte[] buf = new byte[1024]; try { int length = inputStream.read(buf); if(-1 != length){ String reu = new String(buf, 0, length); log.info("---oneAirtightTCPClient_1 -与服务器端交互返回数据:{}",reu); // 截取ffcommand:result1:之后字符串 String str=reu.substring(18, reu.length()); if(!StringUtils.isBlank(str) && !"null".equals(str) && !"#".equals(str)){ if(0 == oneFlg_1){ String airtight[] = str.split(";"); OneAirtight oneAirtight = new OneAirtight(); oneAirtight = oneAirtightService.setOneAirtight(oneAirtight,airtight,"1"); oneAirtightService.insOneAirtightNew(oneAirtight); oneFlg_1 = 1; } }else { oneFlg_1 = 0; } }else { oneFlg_1 = 0; } } catch (IOException e) { log.info("------oneAirtightTCPClient_1 接收数据超时"); try { inputStream.close(); socket.close(); inputStream.close(); log.info("------oneAirtightTCPClient_1 关闭连接"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }