java BufferedReader 长时间连接read不出东西来
RT. 代码如下:
package com.jinshuo;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import
java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import
java.net.SocketTimeoutException;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ClientServer {
private static final Log log = LogFactory.getLog(ClientServer.class);
public static void main(String[] args) {
if(args.length < 3 || args.length > 4){
log.error("参数不合法:" + Arrays.asList(args) + " 程序终止!");
return;
}
log.info("采集程序开始运行:");
log.info("命令参数:" + Arrays.asList(args));
String addrString = args[0];
String portString = args[1];
String timeoutString = args[2];
String sleepString = null;
if(args.length > 3){
sleepString = args[3];
}
Integer port = 0;
try {
port = Integer.decode(portString).intValue();
} catch (Exception e) {
log.error("端口无法转换成数字:" + portString);
log.error("程序终止!");
return;
}
Integer timeout = 10000;
try {
timeout = Integer.decode(timeoutString).intValue();
} catch (Exception e) {
log.error("超时时间无法转换成数字:" + timeoutString + " 使用默认值:" + timeout);
}
Long sleep = 10000L;
if(StringUtils.isEmpty(sleepString)){
log.info("重建连接间隔使用默认值:" + sleep);
}else{
try {
sleep = Long.decode(sleepString).longValue();
} catch (Exception e) {
log.error("重建连接间隔无法转换成数字:" + sleepString + " 使用默认值:" + sleep);
}
}
FaultBufferProcess processThread = new FaultBufferProcess();
BufferedInputStream bufInputStream = null;
BufferedReader reader = null;
String tempString = "";
Socket s = null;
while(true){
while(s == null){
try {
s = new Socket(addrString, port);
s.setReuseAddress(true);
s.setSoTimeout(timeout);
log.info("连接建立成功!");
} catch (Exception e) {
log.error("建立
连接失败!" + Math.round(sleep/1000) + "秒钟后尝试重新连接。");
try {
Thread.sleep(sleep);
} catch (InterruptedException ee) {
// TODO Auto-generated catch block
}
}
}
try {
if ((bufInputStream == null) || (reader == null)) {
bufInputStream = new BufferedInputStream(s.getInputStream());
reader = new BufferedReader(new InputStreamReader(bufInputStream, "GBK"));
log.info("创建读取流成功!");
}
while ((tempString = reader.readLine()) != null)
processThread.bufferFault(tempString);
} catch (
SocketTimeoutException e) {
// TODO: handle exception
log.info("未发现可读内容!"); try {
Thread.sleep(sleep-timeout);
} catch (InterruptedException ee) {
// TODO Auto-generated catch block
}
} catch (
IOException e1) {
// TODO: handle exception
s = null;
reader = null;
bufInputStream = null;
log.error("连接出现异常!" + Math.round(sleep/1000) + "秒钟后尝试重新连接。" , e1);
try {
Thread.sleep(sleep);
} catch (InterruptedException ee) {
// TODO Auto-generated catch block
}
}
}
}
}
package com.jinshuo;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;