0

所以我有这个简单的服务器。当我杀死客户端套接字(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();
    }
}

atm抛出bindException,如何处理。

4

3 回答 3

0

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

于 2012-05-18T13:03:16.740 回答
0

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

更新以澄清,如下所示:

    while(true) {
        //do stuff
    }
} catch (SocketException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
      sock.close();
于 2012-05-17T21:11:31.100 回答
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();
    }
  }
于 2012-05-18T13:18:24.560 回答