繁体   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