任何人都可以让我知道下面的代码有什么问题。为什么不执行while循环块? 我在清单文件中拥有必要的权限。
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 :(得分:0)
“time-b.nist.gov”似乎有问题。我在java项目中尝试了以下简单套接字示例(以简化创建Android项目):
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-b.nist.gov";
:
时间是-b.nist.gov
但如果我将其更改为String hostname = "time.nist.gov";
,我会:
是56438 13-05-26 11:49:57 50 0 0 809.9 UTC(NIST)* at time.nist.gov