简体   繁体   中英

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)?
PS 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM