phcaze
phcaze

Reputation: 1777

Android TCP Sockets timeout

I'm doing an app which needs to communicate with TCP sockets. I set up a Service which is my TCP Server and an activity which is my TCP Client.

I have a big delay from sending a message and receiving an answer from the server, like 10 or more seconds. After some days of researches, I found how to set timeout on the client request and all start to work fine.

So my question is, is it mandatory to set up timeout for a TCP connection, otherwise it doesn't work or something else is wrong with my implementation?

Here's my Client code:

public static void sendTCP(final InetAddress senderAddr, final String Msg, final int serverPort) {
        Thread tclient = new Thread(){
            public void run() {
                boolean connected;
                Socket socket = new Socket();
                try {
                    Log.d("TCP", "Client: Connecting...");
                    socket.bind(null);
                    socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);
                    connected = true;
                try {
                    Log.d("TCP", "Client: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                    out.println(Msg);
                    out.close();
                } 
                catch (Exception e) {
                    Log.e("TCP", "Client: Error sending.", e);
                }
                } catch (Exception e) {
                    Log.e("TCP", "Client: Error connecting.", e);
                    connected = false;
                }
                finally {
                    if (socket != null) {
                        if (socket.isConnected()) {
                            try {
                                socket.close();
                                Log.d("TCP", "Client: Connection Closed.");
                            } catch (IOException e) {
                                Log.e("TCP", "Client: Error closing connection.", e);
                            }
                        }
                    }
                }
            }
        };
        tclient.start();
    }

And Server's:

public void onStart(Intent intent, int startid) {

    t = new Thread(){
         public void run() {
             try {
                Boolean end = false;
                Log.d("TCP", "Server: Creating server.");
                ServerSocket ss = new ServerSocket(TCPPORT);
                while(!end) {
                    //Server is waiting for client here, if needed
                    Log.d("TCP", "Server: Waiting on packet!");
                    Socket s = ss.accept();
                    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    String st = input.readLine();
                    Log.d("TCP", "Server: Message received from client: "+st);

                    InetAddress senderAddr = s.getInetAddress();
                    senderAddrString= senderAddr.getHostAddress();

                    myAddrString = GetLocalIpAddress();
                    myAddr = InetAddress.getByName(myAddrString);

                    if (senderAddr.equals(myAddr)) {
                    }
                    else {
                        //Estraggo dal pacchetto ricevuto
                        try {
                            StringTokenizer tokens = new StringTokenizer(st, "|");
                            flag = tokens.nextToken();
                            userid = tokens.nextToken();
                            payload = tokens.nextToken();
                        }
                        catch (Exception e) {
                            Log.e("TCP", "Server: Errore estrazione dati.");
                        }

                        if (flag.equals(Constants.flag_scan_answer)) {
                            Log.d("TCP", "Server: Flag answer");
                            //devo passare i dati ad un database ScanActivity

                            //database(senderAddrString,userid);

                            System.out.println("RISPOSTA RICEVUTA DAL SERVICE TCP");
                            System.out.println("FLAG " + flag);
                            System.out.println("USERID " + userid);
                            System.out.println("PAYLOAD " + payload);

                            announceReceivingPacket();
                        }

                        else {
                            Log.d("TCP", "Server: CASO NON PREVISTO");
                        }
                    }
                    s.close();
                }
            }
            catch (UnknownHostException e) {
                    e.printStackTrace();
            } 
            catch (IOException e) {
                    e.printStackTrace();
            }
         }
    };
    t.start();
 }

Upvotes: 3

Views: 10808

Answers (2)

grockland
grockland

Reputation: 9

The connect call

socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);

can be BeginConnect with a callback that automatically reports failures and timeouts as well as successful connections. At this point you can use BeginSend and BeginReceive on the socket.

Upvotes: -1

user207421
user207421

Reputation: 310840

it's mandatory to set up timeout for a TCP connection

It isn't mandatory but it's a very good idea. Start by setting it to double or triple the expected service time and adjust so you don't get false positives. The default read timeout is infinity, and I have seen entire platforms fail in a way that wasn't detectable by the reader in any other way than a read timeout.

See here for relevant quotations.

Upvotes: 3

Related Questions