套接字杀死后维护服务器

时间:2012-05-17 21:02:01

标签: java

所以我有这个简单的服务器。当我终止客户端套接字(telnet - >结束进程)时,我想要做的是让服务器保持运行并等待另一个客户端。

private ServerSocket serv;

public Server() throws IOException {

    try {
        serv = new ServerSocket(port);
        serv.setReuseAddress(true);

        while(true) {
            Socket sock = serv.accept();

            try {
                BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);

                while(true) {

                    //do stuff
                }
            } finally {
                sock.close();
            }
        }
    } catch (SocketException e) {
        recreateSocket();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void recreateSocket() {

    try {
        ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port);
        serv = socket;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

它抛出bindException,如何处理它。

3 个答案:

答案 0 :(得分:0)

在finally块之前添加catch语句(但不要在那里调用recreateSocket()

更新澄清,如下:

    while(true) {
        //do stuff
    }
} catch (SocketException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
      sock.close();

答案 1 :(得分:0)

启动一个新线程来处理每个接受的连接。

答案 2 :(得分:0)

原因是您要再次创建服务器套接字。您不需要这样做(前一个仍在工作,这就是您获得绑定异常的原因)。这就是你想要做的:

  private ServerSocket serv;

  public Server(int port) throws IOException
  {

    try {
      serv = new ServerSocket(port);
      serv.setReuseAddress(true);

      while(true) {
        Socket sock = serv.accept();

        try {
          BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);

          // do stuff
        } catch(SocketException e) {
          e.printStackTrace();
        } finally {
          sock.close();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }