2014-08-27 6 views
0

wifi를 사용하여 한 Android 장치를 다른 장치에 연결하려고합니다. 하나의 장치가 핫 스폿을 사용하여 서버로 작동합니다. 다른 장치가 연결되어 있습니다. 그러나 다음 코드를 실행하면 다음과 같은 예외가 발생합니다.android에서 wifi를 통해 서버에 연결할 수 없습니다.

java.net.ConnectException: failed to connect to /192.168.43.198 (port 5555): connect failed: ENETUNREACH (Network is unreachable) 

아래 파일을 사용 중입니다. HostActivity.java

public class HostActivity extends Activity { 
ListView lvHost; 
HostAdapter adHost; 
final String HostTAG = "Host1"; 
    @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_host); 
    WifiManager wifiManager = (WifiManager)this.getSystemService (Context.WIFI_SERVICE); 
    new RetrieveFeedTask2(getApplicationContext()).execute(""); 
       int i =0 ; 
    lvHost = (ListView) findViewById(R.id.lvHost); 
    int j = 0; 
    ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks(); 
    adHost = new HostAdapter(list,this); 
    lvHost.setAdapter(adHost); 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.host, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

}

class RetrieveFeedTask2 extends AsyncTask<String, Context, String> { 
Context ctx = null; 
public RetrieveFeedTask2(Context Dctx) { 
    // TODO Auto-generated constructor stub 
    ctx = Dctx; 
} 
protected String doInBackground(String ...url) { 
    final String HostTAG = "Host1"; 
    final WifiManager wifiManager = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE); 
     try { 
      Boolean end = false; 
      Log.i("test","HostRun"); 
      ServerSocket ss = new ServerSocket(5555); 
      while(!end){ 
       Log.i("test", "HostRun2"); 
        //Server is waiting for client here, if needed 
        Socket s = ss.accept(); 
        Log.i("test", "HostRun3"); 
        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); 
        PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush 
        String st = input.readLine(); 
        Log.i("test", "From client: "+st); 
        System.out.println("From client: "+st); 
        //output.println("Good bye and thanks for all the fish :)"); 
        s.close(); 
        // ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks(); 

      } 
    ss.close(); 


    } catch (UnknownHostException e) { 
      // TODO Auto-generated catch block 
      Log.i("test","host unknown"); 
      e.printStackTrace(); 
    } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 



    return null; 
} 

protected void onPostExecute(String feed) { 
    // TODO: check this.exception 
    // TODO: do something with the feed 
    } 
} 

ClientActivity.java

public class ClientActivity extends Activity { 
final String ClientTAG = "Client1"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_client); 
    WifiManager wifiManager = (WifiManager)getSystemService("wifi"); 
    WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
    int ipAddress = wifiInfo.getIpAddress(); 
     String ip = Formatter.formatIpAddress(ipAddress); 

    new RetrieveFeedTask().execute(ip); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.client, menu); 
    return true; 
} 

} 

class RetrieveFeedTask extends AsyncTask<String, String, String> { 
//Context context; 

protected String doInBackground(String ...urls) { 

    final String ClientTAG = "Client1"; 
    InetAddress ia=null; 
    Log.i("test", "ClientRun1"); 
     try { 
      try { 
       ia=InetAddress.getLocalHost(); 
       Log.i("test",ia.toString()); 
      } catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      Socket s = new Socket("192.168.43.198",5555); 
      Log.i("test", "ClientRun"); 
      //outgoing stream redirect to socket 
      OutputStream out = s.getOutputStream(); 

      PrintWriter output = new PrintWriter(out); 
      output.println("Hello Android!"); 
      BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); 

      //read line(s) 
      String st = input.readLine(); 
      //. . . 
      //Close connection 
      s.close(); 


    } catch (UnknownHostException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 



    return null; 
} 

protected void onPostExecute(String feed) { 
    // TODO: check this.exception 
    // TODO: do something with the feed 
} 

}

나는 인터넷 검색을 시도했다. 많은 사람들이 같은 문제를 언급하고 모든 솔루션을 시도했지만 여전히 연결할 수 없습니다. 도와주세요.

+0

모든 사용 권한에 대한 매니페스트를 확인하셨습니까? – shyam

+0

나는 모든 권한을 부여했습니다. android.permission.ACCESS_WIFI_STATE android.permission.CHANGE_WIFI_STATE android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE – user3482672

+0

110 % 확신 할 수있는 "192.168.43.198"은 호스트 장치의 실제 도달 가능한 주소입니까? 그리고 클라이언트 장치가 같은 네트워크에 있습니까? 그것을 확인하기 위해 Ping-App 종류가 있습니까? – Fildor

답변

0

제안 : 안드로이드에서

  1. Use 10000 < port number <= 65536. (10000보다 작 으면 일부 오류가 발생할 수 있음).
  2. 모바일 네트워크가 활성화되어있는 경우 ServerSocket(port number)은 나가는 IP (모바일 네트워크의 IP)를 사용합니다. 대신 ServerSocket(int port, int backlog, InetAddress localAddress)을 시도하십시오 (주소, 즉 핫스팟의 주소를 지정해야합니다).
  3. ClientActivity.java에서 execute(ip)을 통해 IP를 전달했지만 사용하지는 않은 것으로 나타났습니다. Socket s = new Socket(ip,5555); 할 수 있습니다.
  4. AsyncTask는 오랜 시간 작업을하는 경우에는 권장되지 않습니다. 대신 Thread을 사용하십시오.
관련 문제