首页 > 解决方案 > 如何在 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 温度的持续变化

任何想法?

标签: pythonsocketsudp

解决方案


已经有很多程序可以做到这一点(例如Pi ControlWebmin),所以我自己可能不会这样做。

回答您的问题:有两种可能性:您可以在脚本内多次发送温度,或者您可以多次调用脚本。

第一个选项:

# ----- 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

这将每分钟运行一次脚本。


推荐阅读