两个覆盆子相互通信
Two Raspberries communicating each other
我要准备两个树莓通过 python 程序相互交谈。在开始之前,我会了解哪种方法最简单。更准确地说,Raspberry A 接收到 GPIO 的输入。 python 代码读取 GPIO 的状态并将输入发送到树莓 B,该输入由另一个 python 代码读取。 Raspberry B python 代码向 Raspberry A 发送回一条消息,要求做某事。这两个树莓在同一个网络上。
如何实现两个树莓派之间的网络通信?我应该使用什么来通过网络发送和接收输入?
非常感谢您的帮助
在 Raspberry B 上创建一个 TCP 套接字服务器,在 Raspberry A 上创建一个相应的 TCP 套接字客户端。您会找到大量示例和教程来详细说明如何执行此操作。阅读有关套接字类型和标志的 python 文档。
基本上你必须导入套接字库(import socket)并创建一个套接字对象,像这样:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
在服务器端,您将服务器自己的 IP 地址和任意未使用的端口绑定到套接字,然后开始侦听传入请求:
sock.bind('192.168.1.35', 9050)
sock.listen(1) # allow only 1 connection
connection, client_address = server_socket.accept()
try:
# Receive the data
while True:
data = connection.recv(128) # the buffer in this example is 128 bytes
if data:
:
: do something with the received data and
: send the modified data back as response
:
connection.sendall(data)
else:
break
finally:
# Clean up the connection
connection.close()
在客户端,您同样首先创建一个相应的套接字,然后将其连接到侦听远程服务器的 ip 地址和端口。
sock.connect('192.168.1.35', 9050) # connect to remote server
您可以循环监控您的 GPIO 并使用 sendall 发送数据。请确保服务器端的接收缓冲区足够大以容纳您发送的数据。
# Send data
socket.sendall(data)
# Look for the response
data = client_socket.recv(128) # Make sure the buffer is big enough
完成后可以关闭连接:
client_socket.close()
只要您不需要异步通信或一次不需要多个连接,这基本上就是您通信所需的全部内容。因为我不知道你如何监控 GPIO 以及你想对响应做什么,所以我没有在客户端进一步详细说明。
我要准备两个树莓通过 python 程序相互交谈。在开始之前,我会了解哪种方法最简单。更准确地说,Raspberry A 接收到 GPIO 的输入。 python 代码读取 GPIO 的状态并将输入发送到树莓 B,该输入由另一个 python 代码读取。 Raspberry B python 代码向 Raspberry A 发送回一条消息,要求做某事。这两个树莓在同一个网络上。 如何实现两个树莓派之间的网络通信?我应该使用什么来通过网络发送和接收输入? 非常感谢您的帮助
在 Raspberry B 上创建一个 TCP 套接字服务器,在 Raspberry A 上创建一个相应的 TCP 套接字客户端。您会找到大量示例和教程来详细说明如何执行此操作。阅读有关套接字类型和标志的 python 文档。
基本上你必须导入套接字库(import socket)并创建一个套接字对象,像这样:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
在服务器端,您将服务器自己的 IP 地址和任意未使用的端口绑定到套接字,然后开始侦听传入请求:
sock.bind('192.168.1.35', 9050)
sock.listen(1) # allow only 1 connection
connection, client_address = server_socket.accept()
try:
# Receive the data
while True:
data = connection.recv(128) # the buffer in this example is 128 bytes
if data:
:
: do something with the received data and
: send the modified data back as response
:
connection.sendall(data)
else:
break
finally:
# Clean up the connection
connection.close()
在客户端,您同样首先创建一个相应的套接字,然后将其连接到侦听远程服务器的 ip 地址和端口。
sock.connect('192.168.1.35', 9050) # connect to remote server
您可以循环监控您的 GPIO 并使用 sendall 发送数据。请确保服务器端的接收缓冲区足够大以容纳您发送的数据。
# Send data
socket.sendall(data)
# Look for the response
data = client_socket.recv(128) # Make sure the buffer is big enough
完成后可以关闭连接:
client_socket.close()
只要您不需要异步通信或一次不需要多个连接,这基本上就是您通信所需的全部内容。因为我不知道你如何监控 GPIO 以及你想对响应做什么,所以我没有在客户端进一步详细说明。