Android pinging an web service address - android

I want to implement a feature that will ping an address of web service and if it returns true then the application will run through web services otherwise it will use the database of the device (sqlite).
I wrote the code,
public boolean lookfunc()
{
String name1=name;
boolean reachable=false;
try {
InetAddress address = InetAddress.getByName("192.168.1.56");
reachable = address.isReachable(3000);
System.out.println("address.isReachable(3000)"+reachable);
}
catch (UnknownHostException e){
System.err.println("Unable to lookup ");
}
catch (IOException e){
System.err.println("Unable to reach ");
}
catch(Exception e1){System.out.println("Exception raised");}
return reachable;
}
The address 192.168.1.56 is pinging in command prompt but here in code it always return false.
And web service url is : http://192.168.1.56:8080/WIP/services/ConnectionDAO?wsdl, here also this throwing UnknownHostException.

I don't see a point in pinging. Try to download from the web service, and use the database if that fails.

Related

Implement DNS pre-fetcher/resolver using InetAddress or Runtime.getRuntime().exec() in ANDROID

The HTTP connection to a hostname for the first time takes little longer than subsequent requests. Especially, DNS lookup takes long.
I am trying to implement a basic DNS pre-fetcher/resolver using InetAddress or Runtime.getRuntime().exec() in order to improve the HTTP requests performance in ANDROID java without using any third-party library.
Thank you,
Niz
Try this. It just determines the ip address of the host from its hostname supplied via String param. Hope it helps you.
public boolean webSiteAvailable(String url) {
try {
InetAddress ipAddr = InetAddress.getByName(url);
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
}

Android Serversocket does not seem to accept connections on emulators

I've been trying to implement a simple socket communication between two Android emulators but just can't seem to get it.
My server:
public void run() {
if (SERVERIP != null) {
try {
serverStatus.setText("My IP: " + SERVERIP);
serverSocket = new ServerSocket(6798);
serverStatus.setText("ServerSocket Created");
}
catch(Exception e) {
e.printStackTrace();
}
try {
while (true) {
serverStatus.setText("waiting for client");
Socket client = serverSocket.accept();
serverStatus.setText("Connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = in.readLine();
serverStatus.setText(line);
in.close();
client.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
else
serverStatus.setText("Couldn't detect internet connection.");
}
My Client:
try {
InetAddress ina = InetAddress.getByName("10.0.2.2");
socket = new Socket(ina, 6789);
}
catch (Exception e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Hey Server!");
dispText.setText("sent");
}
catch (Exception e) {
e.printStackTrace();
}
The Client side goes on to display the message "sent" however the Server does not move beyond "waiting for client" (stuck on the blocking accept()).
I've used telnet on my Windows machine to redirect port 6789 to 6798 on the server emulator's console. I've also tried turning off my firewall and the other suggestions posted on the similar questions asked here. Please help as just can't seem to get it and feel like I'm making a very stupid mistake.
Also, can anyone please tell me how it is possible for the Client to move beyond the Socket creation code line if the Server is still stuck on accept(). Or, does it not matter to the client that the Server isn't responding as long as it is listening on the port??
Android emulators are placed behind a virtual firewall/router by design, and cannot see each other, even when they are on the same network. The "Using Network Redirection", as well as "Interconnecting Emulator Instances" part of Google's doc on the emulator explains how to communicate with an emulator instance.
As for your last question. Use the empty constructor for socket, and then use the connect call with a specified timeout.

Use Socket to connect to emulator

I was trying to use SocketServer to setup a server
int i =1, PORT = 6666;
ServerSocket server;
Socket client;
try {
server = new ServerSocket(6666);
for(;;){
client = server.accept();//fail in here
textView.setText("server accept..." + i);
//new MyHttpServer(client, i, PORT).start();
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
textView.setText("Fail...");
}
However, the app always stops in server.accept(). I have already add internet permission for this app. I don't know why?
Update:
I have found the reason. It is because thread cannot start from an Active instance. I was putted server.accept() in onStart without a thread. Now I open a new Runnable for it, then fixed
There could be multiple reasons why your application can not start the server. My initial guess would be that you are trying to run the code on an emulator or a device and you already have some other application listening on that port.
You must check/provide the logcat trace in order to get to the cause of the error.
I think so your app will wait for client with port 6666.
server.accept();// return socket
Above code will return socket if client is available.For more details and clearity you can refer these links::
http://www.happygeek.in/socket-programming-in-android
http://www.edumobile.org/android/android-development/socket-programming/

accessing asp.net web api http service from android

I have a working ASP.NET Web API service running in Visual Studio on my dev box. I can easily get the proper results from either I.E. or FireFox by entering: http://localhost:61420/api/products. But when trying to read it from my Android Project using my AVD I get an exception thrown saying:
localhost/127.0.0.1:61420 - Connection refused.
I know my Android Java code works because I can access the WCF RESTFul service running on my Website (the URLthat's currently commented out). My Android code is pasted below.
So, why am I getting the error when accessing from my Eclipse project but not when accessing it from a browser?
Thanks
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpURLConnection urlConnection = null;
try
{
//URL url = new URL("http://www.deanblakely.com/myRESTService/SayHello");
URL url = new URL("http://localhost:61420/api/products");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String myString = readStream(in);
String otherString = myString;
otherString = otherString + " ";
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
urlConnection.disconnect();
}
}
private String readStream(InputStream is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
}
catch (IOException e)
{
return "" + e;
}
}
}
Visual Studio development web server will only accept connections from the local host and not over the network or other virtual connection. Sounds like AVD is seen as a remote host.
To access the app from anywhere, change the webserver that should be used. Assuming you're using Windows 7 and Visual Studio 2010, make sure you have IIS and all required features installed and set the local IIS as the webserver in your project settings:
It could be necessary to start Visual Studio as a Administrator to run it with local IIS.
Use the actual IP address of your machine ie, http://192.168.0.xx
Only your local machine can access localhost, and if you are on the emulator or a device, it will have a different IP through either NAT or your DHCP from the router.

getSocketAddress() method causes delay which leads to communication lag in Android

I'm developing a UDP responder to handle basic SSDP commands. The purpose of this piece of code is to do auto discovery, so when the server sends a multicast to a specific group all other subscribed devices should send back a UDP packet announcing its presence to the host and port of who sent the multicast. My android device receives and sends the packet just fine but because it takes too long to get back the SocketAddress object from getSocketAddress() method the server times out, closes the listening port and never gets a packet back from the android device.
Here's my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MulticastSocket ms = null;
byte[] packBuf = new byte[128];
try {
ms = new MulticastSocket(32410);
ms.joinGroup(InetAddress.getByName("239.255.255.250"));
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
while (true)
{
DatagramPacket receivedPack = new DatagramPacket(packBuf, packBuf.length);
try {
ms.receive(receivedPack);
Log.d(TAG, "Received data");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String responseStr = "HTTP/1.0 200 OK\n" +
"Content-Type: app\n" +
"Resource-Identifier: 945e7dd5913ab45f1db4f271a1620b9471fb7d4d\n" +
"Name: Test App\n" +
"Port: 8888\n" +
"Updated-At: 1319511680\n" +
"Version: 0.9.3.4-29679ad\n" +
"Content-Length: 23\n\n" +
"<message>test</message>";
byte[] response = responseStr.getBytes();
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
} catch (IOException e2) {
// TODO Auto-generated catch block
Log.e(TAG,"Erro",e2);
}
DatagramPacket outPack;
try {
outPack = new DatagramPacket(response, responseStr.length(), receivedPack.getSocketAddress());
sendSocket.send(outPack);
} catch (UnknownHostException e1) {
Log.e(TAG,"Erro",e1);
}
catch (IOException e) {
Log.e(TAG,"Erro",e);
}
catch (Exception e)
{
Log.e(TAG,"Erro",e);
}
}
}
Any ideas?
thanks in advance,
fbr
The most likely problem is that getSocketAddress() is trying to resolve the DNS name of the IP address, which is timing out either due to it being a multicast address or just general DNS lag.
The InetSocketAddress class has a constructor option needResolved which can control this behavior. Unfortunately, it does not appear that DatagramPacket.getSocketAddress() allows you to specify that you want that set to false.
This is apparently a known issue, with some recent discussion of it here:
Issue 12328: DatagramChannel - cannot receive without a hostname lookup
The thread suggests that this has been fixed in Android 3.0, and offers a couple of workarounds for Android 2.0 which may or may not work.
In your case, you could try creating an InetSocketAddress set to INADDR_ANY and port 0 with needsResolved set to 0, and then pass that in when you create receivedPack. Hopefully receive() will reuse that and remember the setting.
2 things come to mind...
1) What happens when you change:
outPack = new DatagramPacket(response, responseStr.length(), receivedPack.getSocketAddress());
to
outPack = new DatagramPacket(response, responseStr.length(), receivedPack.getAddress(), receivedPack.getPort());
2) I remember having this sort of problem with an embedded Java on a Home Automation system. Our short term solution was to put most of the machine and multicast addresses in the hosts file. Long term we ended up with a local DNS server.
There is a parameter somewhere in the Java Network stack that tells it how long to cache DNS failures in memory. We cranked that number up to, I think, 5 minutes instead of 10 seconds.

Categories

Resources