2013-04-06 71 views

回答

1

我不確定我是否完全理解您的問題,但我會盡力幫忙。所以你想要連接客戶端/服務器無限的時間?因此,請嘗試將服務器客戶端和客戶端本身作爲線程,然後將其放入循環中。試試這個例子。

connection = new Socket("IP",PORT); 
     input = new DataInputStream(connection.getInputStream()); 
     output = new DataOutputStream(connection.getOutputStream()); 
     new Thread(new Runnable() { 

     public void run(){ 
      while(true){ 
      try 
      { 
       System.out.println(">>" + input.readUTF()); 
      } 
      catch(Exception e){ 
       try 
       { 
        input.close(); 
        output.close(); 
        connection.close(); 
       } 
       catch(Exception e2) 
       {} 
      } 
      } 
     } 
     }).start(); 

     Scanner scan = new Scanner(System.in); 

     while(true) 
     { 
      String data = scan.nextLine(); 
      output.writeUTF(data); 
     } 

這是客戶端的代碼。您還必須擁有接受所有數據併發回信息的ClienT Service線程!希望我很有幫助,因爲我不太確定我是否正確地理解了這個問題。祝你好運!

+0

是的我想在客戶端和服務器之間的無限時間連接,即在一個while循環 – 2013-04-06 10:05:19