Search code examples
pythonandroidserverclient

Android client won't receive from python server


Hey I just started to learn android and my task was to make an application that sends and receives data from a python server. it sends the data perfectly but I can't make the client receive the data. please go easy on me I'm new here is my code:

Android Code:

class MyTask extends AsyncTask<Void, Void, Void> {
        @SuppressLint(("Wrong Thread"))
        @Override
        protected Void doInBackground(Void... voids) {

            try {
                Log.d("ORI", "1- before connect");
                sock = new Socket(LOCAL_HOST, PORT);
                Log.d("ORI", "2 - after connect" );
                prWriter = new PrintWriter(sock.getOutputStream());
                prWriter.write(msg);
                prWriter.flush();
                BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG);
                sock.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

And here is my Python server:

import socket

server_sock = socket.socket()
server_sock.bind(("0.0.0.0", 5024))
server_sock.listen(1)

client, addr = server_sock.accept()
print(addr[0])
flag = False
while True:
    try:
        data = client.recv(1024).decode()
    except Exception as e:
        print(str(e))
        break

    else:
        if not flag:
            if data == '':
                pass
            print(data)
            try:
                client.send("K".encode())
            except Exception as e:
                print(e)
            else:
                print("OK")
                flag = True



server_sock.close()

Solution

  • Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)

    Your client tries to read a line using .readLine().

    But.. is your server sending a line? Your server sends:

     client.send("K".encode())
    

    (That is only one character. Why not a big sentence?)

    But anyhow it is only a line when the string ends with \n.

    So change to:

     client.send("Hello World\n".encode())