首页 > 解决方案 > 有没有办法设置 python 套接字,以便服务器仅在客户端要求更新值时发送?

问题描述

我试图从一个 python 脚本中获取一个值到另一个。第一个脚本必须一直运行,接收脚本不能一直运行,需要从第一个获取最新的值。

现在该脚本几乎没有功能。但是由于接收者的运行速度比发送者慢,因此形成了积压。如果发件人没有新数据,我还需要一种方法来使用先前的值继续第二个脚本。否则,程序会在发送方停止时挂起。

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tabletPressure = "Value constantly updates while pen is pressed, value is between 0,4096"

while True:
    if pen_pressed:
        intValue = int(tabletPressure)
        bytesValue = (intValue).to_bytes(4, byteorder="little")
        sock.sendto(bytesValue,("0.0.0.0", 33335))

接收脚本如下所示

import socket
import time

dataBus = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dataBus.bind(('0.0.0.0', 33335))


def modal(self, context, event):

    if event.type in {'RIGHTMOUSE', 'ESC'}:
        self.cancel(context)
        self.dataBus.close()
        return {'CANCELLED'}

    if event.type == 'MOUSEMOVE':
        data, addr = dataBus.recvfrom(4)
        print(int.from_bytes(data, byteorder="little"))

我真的很感激任何帮助!谢谢!

标签: pythonsocketspython-sockets

解决方案


将服务器设置为仅在收到消息时才发送消息。例子:

服务器.py

from socket import *
from threading import Thread
from time import sleep

s = socket(AF_INET,SOCK_DGRAM)
s.bind(('',5000))

counter = 0

def datagram_server():
    while True:
        data,addr = s.recvfrom(4096)                # receive any message
        s.sendto(counter.to_bytes(4,'little'),addr) # respond to client address

Thread(target=datagram_server,daemon=True).start()

while True:
    sleep(.5)
    counter += 1 # constantly updating value

客户端.py

from socket import *
from time import sleep

s = socket(AF_INET,SOCK_DGRAM)
server = 'localhost',5000
ping = b'' # message content doesn't matter

def get_latest_counter():
    s.sendto(ping,server)      # ping server to get a response
    data,addr = s.recvfrom(4)  # get the response
    return int.from_bytes(data,'little')

while True:
    print(get_latest_counter())
    sleep(1)

输出:

5
7
9
11

推荐阅读