2014-12-01 54 views
0

客戶端代碼當我運行客戶端第一次服務器顯示輸出...當我運行客戶端第二次,服務器不會不顯示輸出

try { 
    URL url=new URL("http://127.0.0.1:7655"); 
    HttpURLConnection connection=(HttpURLConnection) url.openConnection(); 
    connection.setDoOutput(true); 
    connection.connect(); 
    PrintWriter writer = new PrintWriter(connection.getOutputStream()); 
    writer.println("Hello"); 

    writer.flush(); 
    writer.close(); 
    connection.getResponseCode(); 
    connection.disconnect(); 
} catch (UnknownHostException e) { 
    System.err.println("Don't know about host: hostname"); 
} catch (IOException e) { 
    System.err.println("Couldn't get I/O for the connection to: hostname"); 
} 

服務器端代碼

public static void main(String args[]) throws IOException { 
    ServerSocket echoServer = null; 
    String line; 
    DataInputStream is = null; 
    Socket clientSocket = null; 

    try { 
     echoServer = new ServerSocket(7655); 
     clientSocket = echoServer.accept(); 
     while (true) { 
      is = new DataInputStream(clientSocket.getInputStream());   
      System.out.println("inside"); 
      line = is.readLine(); 
      System.out.println(line); 
     } 
    }catch (IOException e) { 
     System.out.println(e); 
    }finally{ 
     is.close(); 
     clientSocket.close(); 
    } 
} 

當我第一次運行客戶端時,服務器顯示輸出...第二次當我運行客戶端時,服務器不顯示輸出。代碼中有一些錯誤嗎?

如果我沒有找到最終服務器端的「Connection.getResponseCode」接收到null並在控制檯上顯示爲null。爲什麼這是必要的?

回答

0

您的代碼正是這樣設計的。 您需要在服務器端使用多線程,線程接受所有連接,另一個是您的DataInputStream線程。

我是如何做到這一點的......我有一個類,它是自己的getters和setter,只用於線程之間需要的信息或數組。並且在您的主要運行中,將始終接受連接並讀取每個連接的2個線程。

相關問題