0
我有一個簡單的服務器上運行我的電腦和一個簡單的客戶端上我的HTC運行Android 2.2的慾望。如何獲得簡單的Android客戶端和PC服務器得到工作
服務器和客戶端都使用相同的端口。我將服務器ip硬編碼到客戶端代碼中。當我嘗試連接到使用Android客戶端上的客戶端運行的服務器拋出該異常:
IOException ...: java.net.SocketException: The operation timed out.
下面是客戶端和服務器代碼的部分:
客戶端代碼
InetAddress addr;
Socket socket = null;
byte [] ipAddress = new byte[] {(byte)82,(byte)168,(byte)175,(byte)141};
try{
addr = InetAddress.getByAddress(ipAddress);
socket = new Socket(addr, 1234);
System.out.println("socket = "+socket);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
out.println("hello");
socket.close();
} catch (UnknownHostException e) {
System.out.println("UnknownHostException ...: "+e);
} catch (IOException e) {
System.out.println("IOException ...: "+e);
}
,
服務器代碼
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Started:"+ss);
try{
//block until a connection occures
Socket socket = ss.accept();
try{
System.out.println("Conncetion accepted:"+socket);
InputStream IS = socket.getInputStream();
InputStreamReader ISR = new InputStreamReader(IS);
BufferedReader in = new BufferedReader(ISR);
OutputStream OS = socket.getOutputStream();
OutputStreamWriter OSR= new OutputStreamWriter(OS);
BufferedWriter BW = new BufferedWriter(OSR);
//output automatically flushed by PrintWriter
PrintWriter out = new PrintWriter(BW,true);
while(true){
String str = in.readLine();
System.out.println("Client: "+str);
out.println("hi");
}
}finally{
System.out.println("Closing...");
socket.close();
}
}finally{
ss.close();
}
此代碼使用wifi,但不通過3G。
任何幫助,歡迎...並提前感謝您。
Kengo,謝謝你的回覆。那麼這意味着如果有NAT,就沒有tcp連接?或者有沒有解決這個問題的方法? – mnish 2011-01-31 12:58:39