无法通过android中的wifi连接到服务器

时间:2014-08-27 09:49:56

标签: java android client-server

我正在尝试使用wifi将一个Android设备连接到另一个。一台设备充当使用热点的服务器。另一个设备连接到它。但是,当我运行以下代码时,它会产生以下异常。

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
}

}

我试过谷歌搜索。许多人提到了同样的问题,我尝试了所有的解决方案,但仍然无法连接。请帮忙。

1 个答案:

答案 0 :(得分:0)

一些建议:

    android中的
  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