Я создаю TCP-сервер на Raspberry Pi, чтобы я мог управлять им с моего телефона Android через WIFI.Я подключил и пи, и телефон к своему WIFI-маршрутизатору.
import socket
from cookieLED_FINAL import callLED
host = '192.168.100.100'
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind complete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(filePath):
picFile = open(filePath, 'wb')
print("Opened the file.")
pic = conn.recv(1024)
while pic:
print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024)
picFile.close()
def dataTransfer(conn):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
# Split the data such that you separate the command
# from the rest of the data.
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'STORE':
print("Store command received. Time to save a picture")
storeFile(dataMessage[1])
print("FINISHED STORING FILE")
break
elif command == 'LED_ON':
callLED()
reply = 'LED was on'
elif command == 'EXIT':
print("Our client has left us :(")
break
elif command == 'KILL':
print("Our server is shutting down.")
s.close()
break
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(str.encode(reply))
print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
При использовании IP:
192.168.100.100:
[Errno 99]Невозможно назначить запрошенный адрес
127.162.100.100 или 0.0.0.0: сокет создается, но клиент Android не подключается.
На моем телефоне Android я использую приложение с именемTCP / UDP Test Tool, который я скачал из магазина Play.
Я новичок в Linux, а также в Raspberry Pi 3 B +.
ОС: RASPBIAN
ЯЗЫК ПРОГРАММИРОВАНИЯ:ПИТОН 3.5