Mykhailo Gaidai
Mykhailo Gaidai

Reputation: 3160

Android to PC data exchange via Socket

I have a Java desktop application acting like "server" and an Android application, that should be acting as a "client".
"Client" should send String and receive response String[] from "server". The only method, I've came across is using Sockets like this

Socket socket = null;
    try {
        Log.d(log_tag, "creating socket");
        socket = new Socket("192.168.1.123", 8090);
        Log.d(log_tag, "creating out");
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        DataInputStream in = new DataInputStream(socket.getInputStream());
        Log.d(log_tag, "out created. sending data");
        out.writeUTF("sql");
        Log.d(log_tag, "data sent");
        Log.d(log_tag, "receiving data. loop");
        while(in.available() == 0);
        Log.d(log_tag, "received = " + in.readUTF());
        out.close();
        in.close();
        socket.close();
        Log.d(log_tag, "all closed");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d(log_tag, "finished");

"Server" is built the same way, except for order of operations(first read, then write response).

The problem: Android application freezes on line

while(in.available() == 0);

so, InputStream never gets ready and I can't receive server response, but "server" reports, that the data was sent.
Can you point me to my mistake(it's obvious one, I suppose, but I can't see it)?
P.S. Maybe that's the wrong way, but it's not an option to use any mid-layers here. I can't modify server code too.

Upvotes: 1

Views: 2698

Answers (1)

Mykhailo Gaidai
Mykhailo Gaidai

Reputation: 3160

Kind of necropost :)

The problem was in the "server" code.

In my case it was sending empty UTF string, which can't be received at all(should be at least one space character for InputStream to catch something)

Upvotes: 1

Related Questions