python - 如何在 UDP Socket 上流式传输数据
问题描述
我知道如何使用 Python3 使用以下代码打开 UDP 套接字服务器/客户端并一次传输一个数据,即我的 Raspberry 的 CPU 温度:
客户:
# ----- An UDP client in Python that sends temperature values to server-----
import socket
import time
# Get Raspberry's CPU temperature
def getTemp():
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read())
return temp;
# A tuple with server ip and port
serverAddress = ("127.0.0.1", 7070);
# Create a datagram socket
tempSensorSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
# Get temperature
# while True:
temperature = int(open('/sys/class/thermal/thermal_zone0/temp').read())
tempString = "%.2f"%temperature;
# Socket is not in connected state yet...sendto() can be used
# Send temperature to the server
tempSensorSocket.sendto(tempString.encode(), ("127.0.0.1",7070));
服务器:
# ----- An UDP server in Python that receives temperature values from clients-----
import socket
import datetime
# Define the IP address and the Port Number
ip = "127.0.0.1";
port = 7070;
listeningAddress = (ip, port);
# Create a datagram based server socket that uses IPv4 addressing scheme
datagramSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
datagramSocket.bind(listeningAddress);
while(True):
tempVal, sourceAddress = datagramSocket.recvfrom(128);
print("Temperature at %s is %s"%(sourceAddress, tempVal.decode()));
response = "Received at: %s"%datetime.datetime.now();
datagramSocket.sendto(response.encode(), sourceAddress);
我不知道如何在客户端和服务器之间发送恒定的数据流(Raspberry CPU's temps )。
换句话说:每次启动时client.py
,我都会在服务器上看到实际的树莓派 CPU 温度,但我不知道如何启动客户端并在服务器端实时查看树莓派 CPU 温度的持续变化。
任何想法?
解决方案
已经有很多程序可以做到这一点(例如Pi Control或Webmin),所以我自己可能不会这样做。
回答您的问题:有两种可能性:您可以在脚本内多次发送温度,或者您可以多次调用脚本。
第一个选项:
# ----- An UDP client in Python that sends temperature values to server-----
import socket
import time
# Get Raspberry's CPU temperature
def getTemp():
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read())
return temp;
# A tuple with server ip and port
serverAddress = ("127.0.0.1", 7070);
# Create a datagram socket
tempSensorSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
while True:
# Get temperature
# while True:
temperature = int(open('/sys/class/thermal/thermal_zone0/temp').read())
tempString = "%.2f"%temperature;
# Socket is not in connected state yet...sendto() can be used
# Send temperature to the server
tempSensorSocket.sendto(tempString.encode(), ("127.0.0.1",7070));
time.sleep(30) # seconds
(Python 不需要分号,为什么要使用分号?)
第二个选项(使用cron):
$ crontab -e
* * * * * /usr/bin/python3 /path/to/client.py
这将每分钟运行一次脚本。
推荐阅读
- angular - 如何在 Angular 9 中使用 Validator.pattern
- java - 如何将字符数组转换为集合?
- java - 在 Java 已发送电子邮件的电子邮件正文上显示 SQL 查询中的数据
- postgresql - 在一处为所有序列配置 Postgres 自动递增序列起始值
- java - 在地图中添加项目时出现 ConcurentModificationException
- vue.js - VUE i18n 无法翻译错误信息
- java - 当我按下从数据库中检索数据的更新按钮时,如何立即更改 TextView 的值?
- database - 查询以禁用 Postgres 中特定用户的触发器
- c++ - 返回引用返回函数的局部引用与局部变量
- flutter - 颤振图像选择器maxDuration问题