2012-05-25 75 views
1

嘗試運行echo服務器時,無法讀取/寫入數據到套接字。沒有異常拋出,並且沒有響應控制檯輸入。代碼中有什麼不正確?無法從套接字的InputStream獲取數據

public class Server { 

    static ServerSocket server; 

    public static void main(String[] args) throws IOException { 
     String hostname = "127.0.0.1"; 

     try{ 
      server = new ServerSocket(8888); 
      } catch (IOException e) { 
      System.out.println("Could not listen on port 8888"); 
      System.exit(-1); 
      } 

     Socket theSocket = null; 
     try { 
      theSocket = new Socket(hostname, 8888); 

      BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream())); 
      BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in)); 
      PrintWriter out = new PrintWriter(theSocket.getOutputStream(), true); 
      System.out.println("Connected to echo server"); 

      while (true) { 
       String theLine = userIn.readLine(); 
       if (theLine.equals(".")) 
       break; 
       out.println(theLine); 
       out.flush(); 
       System.out.println("networkIn: "+networkIn.readLine()); 
      } 
      networkIn.close(); 
      out.close(); 
      System.out.println("out.close();"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 


    } 
} 

回答

3

你創建了兩個不相關的插座,一個用於接受連接,和一個用於連接到(主機名,8888)。您需要在服務器套接字上調用accept()以實際連接客戶端。請參閱tutorial

1

首先加入Socket client = server.accept();。然後你會看到你需要如何重構你的程序的其餘部分。