2013-10-12 63 views
0

我有兩個使用套接字的單元測試。問題是,當我在eclipse中執行它們時,在第二個客戶端/服務器測試中,我總是有連接拒絕錯誤。第一單元測試使用端口9091,第二個使用端口9092.執行多個使用Java套接字的單元測試

java.net.ConnectException: Connection refused 
at java.net.PlainSocketImpl.socketConnect(Native Method) 

快速的解決方案是在第二單元測試開始添加Thread.sleep(500)。它主要是有效的,但並非總是如此。

這個錯誤有什麼問題?我怎樣才能安全地執行多個使用套接字的單元測試?

@Test(timeout = 2000) 
public void testBareTest9092() { 

    PingerThread pinger = new PingerThread(); 
    pinger.start(); 

    String serverAddress = "localhost"; 
    String testString = "ABCDEF-Hellowrolds"; 
    try { 
     Socket s = new Socket(serverAddress, 9092); 

     PrintWriter output = new PrintWriter(s.getOutputStream(), true); 
     output.println(testString); 

     BufferedReader input = new BufferedReader(new InputStreamReader(
       s.getInputStream())); 
     String answer = input.readLine(); 
     System.out.println(answer); 
     System.out.println(testString); 
     assertTrue(answer.equals(testString)); 

     s.close(); 
     input.close(); 
     output.close(); 
    } catch (UnknownHostException e) { 
     e.printStackTrace(); 
     fail("ERROR!"); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     fail("ERROR!"); 
    } 
    pinger.cancel(); 
} 

public class PingerThread extends Thread { 
    public int id; 

    @Override 
    public void run() { 
     try { 
      ServerSocket listener = new ServerSocket(9092); 
      long startTime = System.nanoTime(); 
      while (!Thread.currentThread().isInterrupted()) { 
       try { 
        while (true) { 
         Socket socket = listener.accept(); 
         try { 
          BufferedReader in = new BufferedReader(
            new InputStreamReader(
              socket.getInputStream())); 
          String input = in.readLine(); 

          System.out.println("Received:" + input); 

          PrintWriter out = new PrintWriter(
            socket.getOutputStream(), true); 
          out.println(input); 
         } finally { 
          socket.close(); 
          listener.close(); 
         } 
        } 
       } finally { 
       } 
      } 
     } catch (Exception consumed) { 
     } 
    } 

    public void cancel() { 
     interrupt(); 
    } 
} 

回答

0

只要在發生錯誤時重試即可解決此問題。

Socket s; 
try { 
    s = new Socket(serverAddress, 9092); 
} 
catch (IOException e) 
{ 
    // when error, try again after some delay 
    Thread.sleep(500); 
    s = new Socket(serverAddress, 9092); 
} 
相關問題