无法连接到服务器通过WiFi在Android
问题描述:
我想连接一个Android设备到另一个使用WiFi。一台设备充当使用热点的服务器。另一个设备连接到它。但是,当我运行以下代码段时,它会给出以下例外。无法连接到服务器通过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
}
}
我试着用搜索引擎。许多人都提到了同样的问题,我尝试了所有的解决方案,但仍然无法连接。请帮忙。
答
几点建议:
- 在android系统
Use 10000 < port number <= 65536
。 (小于10000, 可能会发生一些错误)。 - 如果移动网络处于活动状态,则
ServerSocket(port number)
将使用外出IP(移动网络的IP)。改为尝试ServerSocket(int port, int backlog, InetAddress localAddress)
(您需要指定地址,即热点地址。) - 在ClientActivity.java中,我看到您通过
execute(ip)
传递IP,但您没有使用它。你可以做Socket s = new Socket(ip,5555);
。 - AsyncTask不推荐用于长时间工作。改为使用
Thread
。
您是否检查过您的清单以获取所有权限? – shyam 2014-08-27 10:30:48
我给了所有的权限即。 android.permission.ACCESS_WIFI_STATE,android.permission.CHANGE_WIFI_STATE,android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE – user3482672 2014-08-27 10:37:54
您确定110%“192.168.43.198”是您的主机设备的实际地址吗?和客户端设备在同一个网络上?你有一些Ping应用程序来检查? – Fildor 2014-08-27 10:58:20