【发布时间】:2018-03-24 06:19:20
【问题描述】:
以下场景可以解释我的问题。
我有一个充当服务器套接字程序的 PLC。我编写了一个客户端 Java 程序,通过套接字通信与 PLC 进行通信。
在这个过程中发生的步骤是:
1) 每秒钟我的客户端程序碰巧与 PLC 通信,读取流中的数据,将数据临时存储在 ByteArrayOutputStream 中并关闭输入流和套接字。下面sn-p给出思路
try {
socket = new Socket(host, port);
is = socket.getInputStream();
outputBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read;
if((read = is.read(buffer)) != -1) {
outputBuffer.write(buffer, 0, read);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
System.out.println("Before closing the socket");
try {
is.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("After closing the socket");
} catch (Exception e) {
e.printStackTrace();
}
}
2)根据我的要求处理存储的数据是我想要做的。所以每 1 秒,客户端程序连接到服务器,读取数据(如果数据存在),存储数据,关闭套接字并处理它。它必须持续很长时间,可能直到服务器程序启动。这可能会每隔几周发生一次。
3) 我面临的问题是,我可以运行上述节目 1-2 小时,但从那时起,客户端程序无法从服务器程序(在这种情况下为 PLC)获取数据,虽然两者都是通过套接字连接的。即存在 128 个字节的数据,但客户端程序无法读取该数据。这在程序成功运行近 2 小时后开始发生
4) 请找到可能对您有所帮助的简短代码。
public class LoggingApplication {
public static void main(String[] args) throws NumberFormatException {
if (args.length > 0 && args.length == 2) {
String ipAddress = mappingService.getIpAddress();
int portNo = (int) mappingService.getPortNo();
ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
execService.schedule(new MyTask(execService, ipAddress, portNo, mappingService), 1000, TimeUnit.MILLISECONDS);
} else {
throw new IllegalArgumentException("Please pass IPAddress and port no as arguments");
}
}
}
可运行代码:
public class MyTask implements Runnable {
public ScheduledExecutorService execService;
private String ipAddress;
private int portNo;
private ConfigurationMappingService mappingService;
private MySocketSocketUtil mySocketSocketUtil;
public MyTask(ScheduledExecutorService execService, String ipAddress, int portNo, ConfigurationMappingService mappingService) {
this.execService = execService;
this.ipAddress = ipAddress;
this.portNo = portNo;
this.mappingService = mappingService;
}
public void run() {
MySocketSocketUtil mySocketSocketUtil = new MySocketSocketUtil(ipAddress, portNo);
execService.schedule(new MyTask(execService, ipAddress, portNo, mappingService), 1000, TimeUnit.MILLISECONDS);
mySocketSocketUtil.getData(); //It's able to fetch the data for almost 2 hours but from then, it's just getting empty data and it's keep on giving empty data from then. and so on.
/*
*
*Some code
*/
}
}
这就是我遇到问题的地方
mySocketSocketUtil.getData(); 能够获取数据近 2 小时,但从那时起,它只是获取空数据并保持从那时起提供空数据。等等。我知道这是一个大问题,我想了解可能出了什么问题。
编辑:我忽略了检查流结束并基于它关闭套接字的条件,因为我知道我只会读取前 1024 个字节的数据。所以,我在 finally 块中关闭了套接字
【问题讨论】: