2015-06-07 156 views
0

我寫了一個服務器在java和android的客戶端,但我無法使用我的android代碼找到服務器。無法連接到服務器(從android模擬器到java服務器)

注1:我在java中使用完全相同的代碼,並且我可以輕鬆連接到服務器。注意2:我使用了「10.0.2.2」和「我的電腦IP」,如在Stackoverflow中的某些線程中提到的,但它們都不起作用。

注3:我採用了android工作室

我將不勝感激,如果有人可以幫助我這一點。

他我把裏面的onCreate:

cl1 = new Client("192.168.189.1"); 

cl1.startRunning(); 

這是我的客戶端類:爲了創建一個使用任何連接 :

package com.example.tavoes; 

import java.io.*; 
import java.net.*; 
import java.util.Scanner; 

import android.util.Log; 

public class Client { 


private ObjectOutputStream output; 
private String message = ""; 
private String serverIp; 
private Socket connection; 
private Scanner scanner; 

// constructor 
public Client(String host) { 
super(); 
serverIp = host; 
} 

// connect to server 
public void startRunning() { 

try { 
    connectToServer();    
    setupStream(); 
    whileChatting(); 
} catch (EOFException eofException) { 
    eofException.printStackTrace(); 
} catch (IOException ioException) { 
    ioException.printStackTrace(); 
} /*finally { 
    closeChat(); 
}*/ 
} 

// connect to server 
private void connectToServer() { 

try { 
    connection = new Socket(InetAddress.getByName(serverIp), 4444); 
} catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 

// setup streams to send and receive messages 
private void setupStream() throws IOException { 
output = new ObjectOutputStream(connection.getOutputStream()); 
output.flush(); 
//input = new ObjectInputStream(connection.getInputStream()); 
//System.out.println("Inside Streams are setup!"); 
} 

// While chatting with server 
private void whileChatting() throws IOException { 
//do { 
//output.flush(); 

output.writeObject("<Request connection \"1\" />"); 

scanner=new Scanner(connection.getInputStream()); 
message = scanner.nextLine(); 
//System.out.println(message); 
//message = (String) input.readObject(); 
} 

// close the streams and sockets 
private void closeChat() { 
try { 
    output.close(); 
    //input.close(); 
    connection.close(); 
    //System.out.println("Closing connection"); 
} catch (IOException ioException) { 
    ioException.printStackTrace(); 
} 
} 
} 
+0

你允許從應用程序的網絡連接?你在真實設備上試過了嗎? –

+0

您需要顯示一些相關的代碼。 –

+0

我把代碼放在第一個andswer – mps

回答

0

只是爲了將其標記爲解決以備將來參考您需要的網絡

  1. 允許應用程序使用網絡通過包括permision 到清單

  2. 是否所有網絡活動在一個單獨的線程 比主線程,或者使用的AsyncTask

相關問題