树莓派和PC间TCP通信
程序员文章站
2022-04-24 11:13:09
...
主要问题
在运行 PC和树莓派socket通信 控制LED.由于树莓派还没有到手,首先在同一台电脑中打开连个终端测试代码,注释掉与树莓派有关所有代码,本文基于Anconda python3.6.2,运行过程中发现
python3报错:TypeError: a bytes-like object is required, not ‘str’
主要是编码问题,
修改以后,测试结果如下所示:
首先打开server端,如下所示:
Client端如下所示:
修改以后代码如下所示:
server.py
// An highlighted block
#import necessary package
import socket
import time
import sys
'''
import RPi.GPIO as GPIO
'''
#define host ip: Rpi's IP
# HOST_IP = "192.168.1.106"注释一部分·
HOST_IP =socket.gethostname() # 获取本地主机名
HOST_PORT = 8888
print("Starting socket: TCP...")
#1.create socket object:socket=socket.socket(family,type)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) )
host_addr = (HOST_IP, HOST_PORT)
#2.bind socket to addr:socket.bind(address)
socket_tcp.bind(host_addr)
#3.listen connection request:socket.listen(backlog)
socket_tcp.listen(3)
#4.waite for client:connection,address=socket.accept()
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip)
socket_con.send(str.encode("Welcome to RPi TCP server!"))
#5.handle
'''
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
'''
print("Receiving package...")
while True:
try:
data=socket_con.recv(512)
data = bytes.decode(data)
if len(data)>0:
print("Received:%s"%data)
if data=='1':
print("It is Open")
# GPIO.output(11,GPIO.HIGH)
elif data=='0':
print("It is Closed")
# GPIO.output(11,GPIO.LOW)
socket_con.send(str.encode(data))
time.sleep(1)
continue
except Exception:
socket_tcp.close()
sys.exit(1)
Client.py如下:
// An highlighted block
import traceback
import socket
import time
import sys
#RPi's IP
# SERVER_IP = "192.168.1.106"
SERVER_IP = socket.gethostname() # 获取本地主机名
SERVER_PORT = 8888
print("Starting socket: TCP...")
server_addr = (SERVER_IP, SERVER_PORT)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT))
socket_tcp.connect(server_addr)
break
except Exception:
print("Can't connect to server,try it latter!")
time.sleep(1)
continue
print("Please input 1 or 0 to turn on/off the led!")
while True:
try:
data = bytes.decode(socket_tcp.recv(512))
if len(data)>0:
print("Received: %s" % data)
command=input()
socket_tcp.send(str.encode(command))
time.sleep(1)
continue
except Exception:
# print("exception")
print(traceback.format_exc())
socket_tcp.close()
socket_tcp=None
sys.exit(1)
参考文章
推荐阅读