编程的新手。.我需要很少的帮助来实现如何在python中完成此特定任务..我需要在PC和andriod之间传输数据。.我尝试了套接字..它仅在活动的互联网连接上起作用(客户端/服务器方法)..我想尝试使用蓝牙或wifi,如果我尝试使用pybluez进行蓝牙.. andriod deos不支持它..并且它仅适用于linux,对于wifi我不知道如何开始/从哪里开始,欢迎提出任何建议
我使用Play商店(python 3.6>)中的python idle3在andriod上运行python脚本,在Windows上我具有python 3.6解释器
答案 0 :(得分:0)
这只是解决wifi,这是我通常使用的一般结构。
服务器脚本:
import socket, os, time, sys, threading
HOST = '192.168.1.2' # The IP address of this server
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg))
sys.exit()
print('Socket bind complete')
#Start listening on socket
s.listen(10)
print('Socket now listening')
#Function for handling connections. This will be used to create threads
def clientthread(conn):
try:
#Sending message to connected client
#print('Welcome to the server. Type something and hit enter')
#conn.send('Welcome to the server. Type something and hit enter\n'.encode()) #send only takes string
data = ""
#infinite loop so that function do not terminate and thread do not end.
toggle = True
count = 0
while True:
data = ""
#Receiving from client
data = conn.recv(1024).decode().strip("\r")
if data:
print(data)
conn.send((data + "\r").encode())
time.sleep(.01)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
#came out of loop
finally:
conn.close()
#now keep talking with the client
while True:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
new_thread = threading.Thread(target = clientthread , args =(conn,))
new_thread.daemon = True
new_thread.start()
s.close()
客户端脚本:
import socket, time
TCP_IP = "192.168.1.2" # The IP address being connected to
TCP_PORT = 8888 # The socket being connected to
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((self.TCP_IP, self.TCP_PORT))
time.sleep(.5)
while True:
s.send("Testing".encode()) # Sends a message
time.sleep(.5)
data = s.recv(64) # Recieves up to 64 bytes, can be more
print("recieved:", data)
time.sleep(.5)
s.close()