2011-11-09 132 views
0

我的Android應用程序應該連接到java tcp服務器時出現問題。我收到Connection拒絕錯誤。Android應用程序和Java服務器問題。拒絕連接

server.java

public class Server 
{ 
public static void main(String argv[]) throws Exception 
{ 
ServerSocket welcomeSocket = new ServerSocket(6789); 
System.out.println("welcome into server"); 
while(true) 
{ 

Socket connectionSocket = welcomeSocket.accept(); 
if (connectionSocket != null) 
{ 
System.out.println(connectionSocket); 
Client client = new Client(connectionSocket); 
client.start(); 
} 
} 
} 
} 

class Client extends Thread 

private Socket connectionSocket; 
private String clientSentence; 
private String ans; 
private String temak="test"; 
private String capitalizedSentence; 
private BufferedReader inFromClient; 
private DataOutputStream outToClient; 

public Client(Socket c) throws IOException 
{ 
connectionSocket = c; 
} 

public void run() 
{ 
try 
{ 
inFromClient = new BufferedReader(new nputStreamReader(connectionSocket.getInputStream())); 
outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 
clientSentence = inFromClient.readLine(); 
System.out.println(clientSentence); 
capitalizedSentence = clientSentence.toUpperCase() + '\n'; 
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
ans = inFromUser.readLine(); 
outToClient.writeBytes(capitalizedSentence); 
if("hej".equals(clientSentence)){ 
outToClient.writeBytes(ans + " tester hej"+ "\n"); 
} 
else{ 
outToClient.writeBytes(ans+"\n"); 
} 
} 
catch(IOException e) 
{ 
System.out.println("Errore: " + e); 
} 
} 
} 

從客戶端片段在Android上:

String sentence = null; 
String modifiedSentence; 
String tempus; 
try { 

Socket clientSocket = new Socket("localhost", 6789); 
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
Log.d("pre","TCP Connected."); 

outToServer.writeBytes(sentence + 'n'); 
modifiedSentence = inFromServer.readLine(); 
Log.d("sentence ", modifiedSentence); 
Log.d("post","TCP Success !!!"); 

clientSocket.close(); 

} catch (Exception e) { 
Log.d("error","TCP Error: " + e.toString()); 
} 

程序試圖在本地主機連接端口6789

+0

您可以編輯您的代碼示例以正確執行縮進操作。現在很難閱讀。 – Gray

+0

localhost是android設備不是你的PC/Mac/Whatever – Selvin

+0

那麼如何獲得設備外?把我的IP? – iie

回答

1

根據例如(編輯:) this Selvin寫道,你應該使用IP地址10.0.2.2連接到運行模擬器的PC。 (localhost127.0.0.1從仿真器內部循環回仿真器。)