基于树莓派的tcp服务器Python代码
时间: 2024-01-23 14:03:19 浏览: 67
基于pythonsocket的tcp服务器
以下是基于树莓派的TCP服务器Python代码的示例:
```python
import socket
# 创建TCP socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_address = ('0.0.0.0', 8080)
server_socket.bind(server_address)
# 开始监听
server_socket.listen(1)
print('Waiting for connection...')
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print(f'Connection from {client_address}')
# 接收客户端数据
while True:
data = client_socket.recv(1024)
if not data:
break
print(f'Received {data} from {client_address}')
# 发送响应给客户端
response = 'Hello, client!'
client_socket.sendall(response.encode('utf-8'))
# 关闭连接
client_socket.close()
server_socket.close()
```
该代码创建了一个TCP服务器,绑定了树莓派的IP地址和端口号8080。它等待客户端连接,一旦连接成功,就接收客户端发送的数据,并将其打印到控制台上。然后,它向客户端发送一条简单的响应消息“Hello, client!”。最后,它关闭连接。
阅读全文