Java Server在两小时后停止

时间:2014-12-19 08:31:30

标签: java sockets

你好everybady我有简单的服务器通过tcp接收文件通常工作正常但如果请求不是来自客户端2小时,我的服务器是无关。如果客户端想要从服务器2小时后请求,服务器没有做。 你有什么建议

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
/* w  ww . jav  a 2 s . c  o m*/


public class Main extends Thread {
  private ServerSocket serverSocket;
  public final static int FILE_SIZE =128*1204;//128k 
  int bytesRead;

  public Main () throws IOException {
    serverSocket = new ServerSocket(1072);

  }

  public void run() {

      BufferedInputStream bis=null; 

      System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
      Socket client=null;

try {
        client = serverSocket.accept();
        System.out.println("1:"+client.getKeepAlive());
        client.setKeepAlive(true);

    } catch (IOException e1) {
        e1.printStackTrace();
    }

      System.out.println("Just connected to " + client.getRemoteSocketAddress());

while (true) {

   try {

        byte [] mybytearray_rec  = new byte [FILE_SIZE];
        bis = new BufferedInputStream(client.getInputStream());
        String s=null;
        while(bis.available()>0)
        {
        bytesRead =bis.read(mybytearray_rec); 
        s = new String(mybytearray_rec,0,bytesRead);
        System.out.print(s);
       }

      } catch (SocketTimeoutException s) {
          System.out.println("SocketTimeoutException:"+s);
          break;
      } catch (IOException e) {
         System.out.println("IOException:"+e);
         e.printStackTrace();
        break;
      }catch (Exception e) {
       System.out.println("Exception:"+e);
       e.printStackTrace();
       break;
     }


    }//While;



  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Thread t = new Main ();
      t.start();
     } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

1 个答案:

答案 0 :(得分:2)

正如您目前的问题所写,这只是对可能发生的事情的猜测。

while循环的位置表明服务器的以下逻辑(伪代码):

LISTEN for a client
ACCEPT a client
LOOP
    PROCESS A TRANSATION with client
    [ wait next message possibly 2 hours]

那是错的。网络中可能有许多组件将中止非活动连接,因为它保留了未使用的资源。

您应该使用:

LISTEN for a client
LOOP
    ACCEPT a client
    PROCESS A TRANSATION with client
    CLOSE the connection
    [ wait next message possibly 2 hours]

这样连接正常关闭而不是保持非活动状态,客户端为每个新事务打开一个干净的连接。