[英]How can I establish a communication between an android device an a python script?
我正在尝试创建一个与正在运行的python脚本通信的android应用。 两者都连接到同一网络,我想通过套接字在它们之间发送一些文本。 我尝试过多次尝试,但是没有一个起作用。 这是我当前的代码:
python部分:
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部分:
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;
}
}
从如何极客 :
0.0.0.0是不可路由的元地址,用于指定无效,未知或不适用的目标(“无特定地址”占位符)。
在服务器的上下文中,0.0.0.0表示本地计算机上的所有IPv4地址。 如果主机有两个IP地址192.168.1.1和10.1.2.1,并且主机上运行的服务器侦听0.0.0.0,则在这两个IP上都可以访问它。
简短的答案是,您可以在服务器端使用0.0.0.0
来使您的服务器在任何地址中侦听,但是对于客户端写入该地址没有意义,您必须向客户端提供服务器的实际地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.