簡體   English   中英

Java 套接字如何模擬與服務器斷開連接

[英]Java Socket how to simulate disconection from server

我有一個帶有客戶端和服務器 sockets 的 Java 程序,我想測試服務器關閉后是否引發異常。

這是服務器:

public class SocketServer implements Runnable {
  private bool serverRuns = false;
  private int timeout = 10000;
  private DataInputStream in;
  private DataOutputStream out;
  private Socket client;
  private ServerSocket server;
  private String message = "Ok";
  private waitForInstruction = true;


  public SocketServer() throws IOException {
    ServerSocket server = new ServerSocket(tcpPort,0,ipAdress);
    serverRuns = true;
    server.setSoTimeout(timeout)
  }

  private void waitForClient() {
    try {
      client = server.accept();
      client.setSoTimeout(timeout);
      in = new DataInputStream(client.getInputStream());
      out = new DataOutputStream(client.getOutputStream());
    } catch (IOException e) {
      fail("I/O Error " + e.getMessage());
    }
   }

  public void run() {
    waitForClient();

    while (serverRuns) {
      if (clientSocket.isClosed()) {
         waitForClient();
      }

      try {
        while (waitForInstruction == false) {
          // Read input message
          String inputStreamString = "";
          while (in.available() > 0) {
            int c = in.read();
            inputStreamString += (char) c;
          } 
          out.write(message.getBytes());
          System.out.println("Sent bytes: " + out.size());
          setWaitForInstruction(true);
        }
      } catch (IOException E) {
        fail("I/O Error " + E.getMessage());
      }
    }
  }


public void closeServerSocket() {
    try {
      serverRuns = false;
      serverSocket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

void setWaitForInstruction(boolean waitForInstruction) {
    this.waitForInstruction = waitForInstruction;
  }
    
  public void startServerSocket() {
    serverRuns = true;
  }
}

這是客戶端:

public class SocketClient extends Socket {
  private InetAddress address;
  private short tcpPort;
  private DataInputStream in;
  private DataOutputStream out;
  private static final int timeOut = 10000;

  public SocketClient(InetAddress address, short tcpPort) {
    this.tcpPort = tcpPort;
    this.address = address;
  }
  public void connect() throws IOException, SocketTimeoutException {
    super.connect(new InetSocketAddress(address, tcpPort), timeOut);
  }

  public void doStuff() throws IOException {
    String request = "Ok?";
    String InputStreamString = "";

    super.setSoTimeout(timeOut);
    this.setSoTimeout(timeOut);
    out = new DataOutputStream(super.getOutputStream());
    in = new DataInputStream(super.getInputStream());

    out.writeBytes(requestString);

    int c;
    do {
      if (in.available() > 0) {
        c = in.read();
        InputStreamString += (char) c;
      }
    } while (!InputStreamString.equals("Ok"));
    System.out.println(InputStreamString);

  }
}

我啟動服務器套接字線程:

 @BeforeClass
 public static void startSocket() throws IOException {
      testServer = new SocketServer();
      monitor = new Thread(testServer);
      monitor.setName("Test Server Thread");
      monitor.setDaemon(true);
      monitor.start();
  }

JUnit 測試是這樣的:

@Before
public void createSocket() throws Exception {
  ipAdress = InetAddress.getLocalHost();
  SystemConfig.setLoggerConfigFilePath("LoggerConfig.xml");

  socketClient = new SocketClient(ipAdress, 5000);
}


@Test
  public void checkServerisDown() {
    try {
      socketClient.connect();
    } catch (IOException e) {
       fail("IO Error");
    }

    testServer.closeServerSocket();
    monitor.interrupt();

   try {
     testServer = new SocketServer();

     monitor = new Thread(testServer);
     monitor.setName(" Test Server Thread");
     monitor.setDaemon(true);
    // monitor.start();

    testServer.startServerSocket();
    testServer.setWaitForInstruction(false);

    System.out.print("Test (1/1) CHECK SERVER IS DOWN.....\n");
    socketClient.doStuff();
    System.out.println("NOT OK!");

  } catch (IOException e) {   
    fail("IO Error " + e.getMessage() + " OK"); 
  }

  try {
    drEstimControlInterface.close();
    testServer.getSocket().close();
  } catch (IOException e) {
    fail("IO Error");
  }
}

  @AfterClass
  public static void closeSocket() throws IOException {
    testServer.closeSocket();
  }

但是測試沒有按我的預期執行,我認為這應該返回一個 IOException,因為服務器套接字已關閉並且線程已被中斷,但客戶端套接字仍然從服務器套接字獲得答案並打印“NOT OK” .”? 誰能告訴我為什么?

您不僅要關閉ServerSocket ,還要關閉帶有流的客戶端套接字。

public void closeServerSocket() {
    try {
      serverRuns = false;
      serverSocket.close();
      in.close();
      out.close();
      client.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM