Socket监听几个小时后就终止
服务器端监听gps发过来的信息,采用tcp方式。可是每次执行几个小时或一天多的时候就会终止,接受不到了。重启服务后又正常。求解决方法。
服务器代码:
public void startSocket() throws Exception {
serverSocket=new ServerSocket(port);
executorService = Executors.newCachedThreadPool();
System.out.println("服务器启动");
while(true){
Socket socket=null;
try {
//接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
socket=serverSocket.accept();
executorService.execute(new Handler(socket));
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Handler implements Runnable{
private Socket socket;
public Handler(Socket socket){
this.socket=socket;
}
public void run(){
try {
System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort());
InputStream socketIn = socket.getInputStream();
int count = 0;
while (count == 0) {
count = socketIn.available();
}
while(true){
byte[] by = new byte[count];
socketIn.read(by);
// do something
}
} catch (
IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
------解决方案--------------------
是不是连接没有释放,后续的就连不上了