我正在创建一个与PC连接的Android应用程序。我正在使用我发现的解决方案HERE 当我尝试通过提供准确的IP地址与PC连接时,一切正常。手机与PC快速连接或(当PC上的服务器不运行时)我得到有关无法快速连接的信息。这是代码:
public class ConnectPhoneTask extends AsyncTask<String,Void,Boolean> {
@Override
protected Boolean doInBackground(String... params) {
boolean result = true;
try {
InetAddress serverAddr = InetAddress.getByName(params[0]);
socket = new Socket(serverAddr, Constants.SERVER_PORT);//Open socket on server IP and port
} catch (IOException e) {
Log.e("remotedroid", "Error while connecting", e);
result = false;
}
return result;
}
@Override
protected void onPostExecute(Boolean result)
{
isConnected = result;
Toast.makeText(context,isConnected?"Connected to server!":"Error while connecting",Toast.LENGTH_LONG).show();
try {
if(isConnected) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true); //create output stream to send data to server
}
}catch (IOException e){
Log.e("remotedroid", "Error while creating OutWriter", e);
Toast.makeText(context,"Error while connecting",Toast.LENGTH_LONG).show();
}
}
}
但是当我尝试遍历IP地址以找到我能够连接到它的设备时需要很长时间,直到超时。这是代码:
public class DevicesListTask extends AsyncTask<String,Void,List<Device>>
{
@Override
protected void onPreExecute() {
pb.setVisibility(ProgressBar.VISIBLE);
}
@Override
protected List<Device> doInBackground(String... params) {
List<Device> devices=new ArrayList<Device>();
String device_ip;
Socket socket;
for(int i=0;i<4;i++)
{
device_ip=params[0]+Integer.toString(i);
try {
InetAddress serverAddr = InetAddress.getByName(device_ip);
socket = new Socket(serverAddr, 8988);
devices.add(new Device(device_ip,socket.getInetAddress().getHostName()));
} catch (IOException e) {
Log.e("remotedroid", "Error while connecting", e);
}
}
return devices;
}
@Override
protected void onPostExecute(List<Device> devices) {
pb.setVisibility(ProgressBar.INVISIBLE);
if(devices!=null)
{
Intent intent = new Intent(context,DevicesList.class);
String[] devicesIPS = new String[devices.size()];
String[] devicesNames = new String[devices.size()];
for(int i=0;i<devices.size();i++)
{
devicesIPS[i]=devices.get(i).getIP();
devicesNames[i]=devices.get(i).getName();
}
intent.putExtra("DEVICES_IPS",devicesIPS);
intent.putExtra("DEVICES_NAMES",devicesNames);
startActivity(intent);
}
else
{
Toast.makeText(context,"nope",Toast.LENGTH_LONG).show();
}
}
}
我只是在上面链接的示例中更改了一些代码。这段代码有什么问题?
我得到的例外是:
java.net.ConnectException: failed to connect to /192.168.1.2 (port 8988): connect failed: ETIMEDOUT (Connection timed out)
我在尝试连接到我的电脑时得到它,但是我只是在循环通过地址而不是在第一个例子中得到这个例外。使用第一个示例中的代码时,我立即连接。连接超时的第二位代码有什么错误?
答案 0 :(得分:1)
当您尝试连接到不存在的IP地址时,您将获得连接超时。默认超时大约一分钟。如果您获得连接超时,可以按如下方式缩短它们:
Socket socket = new Socket(); // create an unconnected socket
int timeout = 5000; // in milliseconds, tune as required
socket.connect(new InetSocketAddress(serverAddr, 8989), timeout);
在大多数情况下,5秒绰绰有余,你可以将其工作到2-3秒,而不是更少。
答案 1 :(得分:0)
您是否在应用的清单文件中设置了互联网权限?如果没有,那么Android就会阻止你。