2013-05-26 34 views
0

任何人都可以讓我知道在下面的代碼中有什麼錯誤。爲什麼它不執行while循環塊? 我在清單文件中擁有必要的權限。Android中的簡單插座示例問題

public class MainActivity extends Activity { 

static TextView t; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    t=(TextView)findViewById(R.id.txt); 
    NetConnect th=new NetConnect(); 
    th.start(); 
} 
public class NetConnect extends Thread { 
    public void run(){ 
     try{ 
      runOnUiThread(new Runnable(){public void run(){t.append("Thread start...");}}); 
      Socket client = new Socket("time-b.nist.gov", 13); 
      BufferedReader in =new BufferedReader(new InputStreamReader(client.getInputStream())); 
      String str; 
      while((str=in.readLine())!=null) 
       t.append(str); 
     }catch(Exception e){ 
      Log.e("Internet:",e.toString()); 
     } 
    } 
} 
+0

您是否在LogCat中看到任何錯誤?我想象一個異常正在被拋出。 –

+0

順便說一句你應該關閉BufferedReader和套接字。 –

+0

關閉部分是好的亞歷杭德羅..我需要關閉..沒有錯誤,沒有任何打印在LogCat –

回答

0

「time-b.nist.gov」似乎存在問題。我試圖在Java項目下面這個簡單的例子插座(爲了簡化對創建Android項目):

正是在time-b.nist.gov

:如果 String hostname = "time-b.nist.gov";

import java.io.IOException; 
import java.io.InputStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 

public class TestSocketClass { 

    public static void main(String[] args) { 
     String hostname = "time-b.nist.gov"; 

     try { 
      Socket theSocket = new Socket(hostname, 13); 
      InputStream timeStream = theSocket.getInputStream(); 
      StringBuffer time = new StringBuffer(); 
      int c; 
      while ((c = timeStream.read()) != -1) 
       time.append((char) c); 
      String timeString = time.toString().trim(); 
      System.out.println("It is " + timeString + " at " + hostname); 
     } // end try 
     catch (UnknownHostException ex) { 
      System.err.println(ex); 
     } catch (IOException ex) { 
      System.err.println(ex); 
     } 
    } 
} 

沒有返回

,但如果我將其更改爲String hostname = "time.nist.gov";我得到:

它是56438 13-05-26 11:49:57 50 0 0 809.9 UTC(NIST)*在 time.nist.gov