简体   繁体   中英

How can I establish a communication between an android device an a python script?

I am trying to create an android app that communicates with a running python script. Both are connected to the same network and I want to send some text between them via sockets. I tryed to do it on multiple attempts but none of them worked. This is my current code :

python part:

import socket
import time

#Defines Server Values
listensocket = socket.socket()
Port = 8000
maxConnections = 999
IP = socket.gethostname() #Gets Hostname Of Current Macheine

listensocket.bind(("0.0.0.0",Port))

#Opens Server
listensocket.listen(maxConnections)
print("Server started at " + IP + " on port " + str(Port))

#Accepts Incomming Connection
(clientsocket, address) = listensocket.accept()
print("New connection made!")

running = True

#Main
while running:
    message = clientsocket.recv(1024).decode() #Receives Message
    if not message == "":
        print(message)
    # closes Server If Message Is Nothing (Client Terminated)
    else:
        clientsocket.close()
        running = False

android part :

class send extends AsyncTask<Void,Void,Void> {
    Socket s;
    PrintWriter pw;
    @Override
    protected Void doInBackground(Void...params){
        try {
            s = new Socket("0.0.0.0",8000);
            pw = new PrintWriter(s.getOutputStream());
            pw.write(message);
            pw.flush();
            pw.close();
            s.close();
        } catch (UnknownHostException e) {
            System.out.println("Fail");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Fail");
            e.printStackTrace();
        }
        return null;
    }
}

From how to geek :

0.0.0.0 is a non-routable meta-address used to designate an invalid, unknown, or non-applicable target (a 'no particular address' place holder).

In the context of servers, 0.0.0.0 means all IPv4 addresses on the local machine. If a host has two IP addresses, 192.168.1.1 and 10.1.2.1, and a server running on the host listens on 0.0.0.0, it will be reachable at both of those IPs.

short answer is you can use 0.0.0.0 on the server side to make your server listen in any address, but it does not make sense for client to write to this address, you have to provide the client with the actual address of the server.

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