python - 有没有办法设置 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"))
我真的很感激任何帮助!谢谢!
解决方案
将服务器设置为仅在收到消息时才发送消息。例子:
服务器.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
推荐阅读
- firebase - Firebase 获取基于角色的文档
- reactjs - 用于生成布局的 Gatsby 动态路由 URL
- python - 正则表达式查找带或不带 www 的有效 URL,包括点但不包括双点
- python - 为什么在安装 ZS 库 Python 时会出现此错误?错误:命令出错,退出状态为 1:命令:path/python -u -c 'import sys,
- node.js - 致命错误:CALL_AND_RETRY_LAST 分配失败 - JavaScript 堆内存不足构建 Angular 应用程序
- python - 当我把我的 .py 变成一个可执行文件时,它会弄乱程序。(自动 py 到 exe)
- python - 如何在我的 Flask 应用程序中登录到 systemd 日志而不是 syslog?
- android - 如何以编程方式退出应用程序固定?
- javascript - 如何重构两种不同类型的子类的实现,同时保留其方法的功能和命名?
- php - 将对象函数作为回调传递