繁体   English   中英

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

[英]Is there a way to set up a python socket so that the server only sends when the client asks for an updated value?

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

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

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)

Output:

5
7
9
11

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM