Application using socket freezes when it tries to connect to server - android

I am doing application which send some data from mobile phone to PC. Im using socket to do it. When the server is online it works, but when I try to connect with wrong ip/port or server is not running then application freezes and I cant do nothing. It because client on mobile phone tries to connect to server.
I have main class in which I make:
Thread cThread = new Thread( new TCPClient( ip, port, message, context) );
cThread.start();
There is context in new TCPClient because i need to make Toast when message is sent or when error appears. In TCPClient class there is:
public void run(){
try {
InetAddress serverAddr = InetAddress.getByName(s_ip);
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, s_port);
When server is online it goes to:
Log.d("TCP", "C: Sending: '" + s_msg + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(s_msg);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
but when the server is offline or I put wrong ip/port my application freezes. I cant do nothing for a while.
Is there any solution to force stop trying connect to server after some time? For example after 5 second application will go to catch and give me error.
I tried to do this with AsyncTask, then application is working even when Client tries to connect to server, but toast with error appears after not acceptable time for me, so I would like a solution which will give me error when client cannot connect with server in for example 5 seconds.

You can set the connection timeout. You have to use different constructor of Socket class. Insead of:
Socket socket = new Socket(serverAddr, s_port);
use:
Socket socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, s_port), 5000);
In case of timeout an exception is thrown.

Perhaps you didn't set a timeout connection so it's "0" by default which means that it will never timeout , so you can set the timeout to 1 minute it won't freeze for more than one minute .

Related

UDP packets sent by Android application over wifi sometimes not received by android devices

I have built a client-server application in Android(Compiling with java-6) to send and receive udp packets.
My client code is as follow:
DatagramSocket socket =new DatagramSocket();
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(dgram, dgramLength, host, port);
socket.send( packet );
socket.close();
My server code is as follows:
DatagramSocket socket =new DatagramSocket(this.port);
byte[] data=new byte[512];
DatagramPacket packet = new DatagramPacket(data, data.length) ;
// Wait for a response from the server
try
{
socket.receive(packet) ;
}
catch (Exception e)
{}
The issue that I am facing is that when I am working on a wired network then all the sent packets are being received by master properly but when I am running the same code over wifi then sometimes sent packets are being received and sometimes not. I want to know that whether it is the general behavior of a wifi network or not.
Any kind of help is appreciated.

Android tcp connection from client

I'm trying to make my android phone a client to a server I wrote in python. The server works good (I have tried it) but I can't seem to connect the phone with the server.
This is the function that should create the connection:
public String createConnection() throws IOException{
InetAddress serverAddr = InetAddress.getByName(ipString);
clientSocket = new Socket(serverAddr, portNumber);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(Client.INIT_HEY.name());
String ans = inFromServer.readLine();
return ans;
}
ipString is the server ip received by the user, portNumber is the port number and they are both correct.
When I try to connect to the server, I receive "null" as the error message.
Any thoughts?
Thanks!
Try it over wifi.
If you can find the phone's IP address, try ping it from your dev system.
If your are on cell network, try access web site from browser, make sure the network connection is working.
The error was because I was running a tcp connection on the main thread.. I could've fixed it by making the class an AsyncTask but I prefered adding this:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Thanks all!

Receive UDP packets on Android

I try to send and receive UDP packets continuously between an Android app and a server.
Is there any way to make that happen ?
My current networking code (running in a Thread) is shown bellow. The client is connected through 3G. The port configured client side is 1088.
The server just echo the packet to the client when received.
The server receive the packet correctly from the client but the client doesn't receive anything back.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.d(TAG, "S: Connecting...");
DatagramSocket socket = new DatagramSocket();
DatagramSocket receive_socket = new DatagramSocket(SERVERPORT, InetAddress.getByName("0.0.0.0"));
while(running) {
DatagramPacket packet_send = new DatagramPacket(msg, msg.length, serverAddr, SERVERPORT);
Log.d(TAG, "C: Sending: '" + new String(msg) + "'");
socket.send(packet_send);
// Prepare a UDP-Packet that can contain the data we want to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
Log.d(TAG, "S: Receiving...");
// Receive the UDP-Packet
receive_socket.receive(packet);
Log.d(TAG, "S: Received: '" + new String(packet.getData()) + "'");
synchronized (this) {
wait(500);
}
}
I suspect the 3G connection is NATed (the server reports a port different from 1088).
If so, is there anything I can do to overcome that ?
Or is there anything wrong I do in my code ?
Turned out the code was working fine, the 3G service provider was blocking some UDP packets.

Android socket bind exception

i am new to Android networking concepts.Now i am trying to connect my server and close the socket.after that i am create a new socket with old ip and port.It causes address already in use exception? can any one help me.below is my following code
Socket socket=new Socket("122.165.81.120",10200);
int port=socket.getLocalPort();
socket.shutdownInput();
socket.shutdownOutput();
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
Socket socket2=new Socket();
SocketAddress myaddress = new InetSocketAddress("172.16.1.37",port);
socket2.bind(myaddress);
socket2.close();
You need to set the SO_REUSEADDR socket option. This is done with the Socket.setReuseAddr function.

Android, problems with SocketAddress and sockets. Reverse lookup?

i have a problem with Android. I am trying to connect to a server with a proxy with no luck.
I have this code that works fine on normal Java. It only defines a proxy server and creates a socket that would connect to google with that proxy. It sends a simple GET request and then shows the response.
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
public class Main {
public static void main(String[] args) {
try{
//create the proxy info
SocketAddress socketAddress = new InetSocketAddress("78.137.18.67" , 8364);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socketAddress);
// create the socket with the proxy
Socket socket = new Socket(proxy);
// connect to some address and send/receive data
socket.connect(new InetSocketAddress("www.google.com", 80));
socket.getOutputStream().write("GET /index.html HTTP/1.1\r\nHost: www.google.com\r\n\r\n".getBytes("UTF-8"));
byte result[] = new byte[1024];
socket.getInputStream().read(result);
socket.close();
System.out.println(new String(result));
}catch(Exception e){
e.printStackTrace();
}
}
}
The problem with android, with a code similar like that, is that the InetSocketAddress is doing something strange. It seems that it does a reverse lookup of the given ip, and then the socket created with the proxy tries to connect with the resolved host name, in this case is 78-137-18-67.dynamic-pool.mclaut.net.
This would not be a problem (except on performance) if the socket could resolve the hostname back to the ip address. The fact is that this hostname cannot be resolved to ip address with my internet connection (i don't know if others can do). So the reverse lookup is working fine but the normal lookups fails, so when the socket tries to connect through the proxy it raises the following exception:
08-25 19:26:46.332: ERROR/Microlog(3526): 40274 SocketConnection
[ERROR] Error establishing connection java.net.SocketException: SOCKS
connection failed: java.net.UnknownHostException:
78-137-18-67.dynamic-pool.mclaut.net
So the question is, why it is trying to connect with the hostname if i gave the ip address? Is there any way to avoid this lookup? I have tried with createUnresolved of InetSocketAddress but in this case the socket hangs on connection.
Is not a waste of time, internet connection, etc, to do a reverse DNS lookup to get the hostname (if any), and later when the socket needs to connect, resolve again the host to an ip address?
NOTE: this code is an example, the real app do not perform any http request in this way. It uses binary data packets.
To prevent a reverse lookup, you can create the InetAddress with getByAddress(byte[]).
Then pass the InetAddress instance into the InetSocketAddress constructor.
Alternatively, use the factory method InetSocketAddress.createUnresolved(String,int)
Yes it seems that the particular constructor of InetSocketAddress does a reverse DNS lookup: http://mailinglists.945824.n3.nabble.com/Android-and-reverse-DNS-lookup-issues-td3011461.html
Also, it seems that this does not happen anymore on Android 2.3.4.
In android you have to do everything with background process so that you do not write code for socket in onCreate method directly you have to do this in background so that your ui does not hangs
something like this
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(ipaddress, port);
printwriter = new PrintWriter(client.getOutputStream(), true);
InputStream is = client.getInputStream();
printwriter.write(msg);
printwriter.flush();
byte[] buffer = new byte[2046];
int read;
while ((read = is.read(buffer)) != -1) {
final String output = new String(buffer, 0, read);
);
printwriter.close();
}
});
}
Log.e("message", "message send");
} catch (UnknownHostException e2) {
e2.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
Log.d("Time out", "Time");
}

Categories

Resources