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
在Raspberry B上创建一个TCP套接字服务器,在Raspberry a上创建一个相应的TCP套接字客户端。您将发现大量的示例和教程详细介绍如何执行此操作。阅读有关套接字类型和标志的python文档。
基本上,您必须导入socket库(import socket)并创建一个socket对象,如下所示:
在服务器端,将服务器自身的ip地址和任意未使用的端口绑定到套接字,然后开始侦听传入的请求:
在客户端,再次首先创建相应的套接字,然后将其连接到正在侦听的远程服务器ip地址和端口。
您可以在循环中监视GPIO,并使用sendall发送数据。确保服务器端的接收缓冲区足够大,可以容纳您发送的数据。
完成后可以关闭连接:
这基本上就是您的通信所需的一切,只要您不需要异步通信或一次连接多个。由于我不知道你如何监控GPIO,以及你想对响应做什么,所以我没有深入了解客户端的更多细节。
相关问题 更多 >
编程相关推荐