Python:以时间间隔发送数据的套接字

时间:2017-07-25 07:43:11

标签: python python-2.7 python-sockets

我开发了一个代码,其中,我每秒都从串口读取数据。相同的数据我必须将数据发送到任何IP和端口,但具有特定的时间间隔,如10s,30s等。

那么如何告诉socket进入睡眠状态,它不会每秒发送一次数据?

3 个答案:

答案 0 :(得分:2)

你不需要告诉套接字进入睡眠状态,套接字应该一直在监听。你可以做的是让你的程序轮询套接字每隔一秒就进入睡眠状态

import time
while(true):
  sock.recv()
  time.sleep(1)

或者如果您想要更冒险,可以使用epoll循环来检查您的套接字是否收到任何内容。 epoll循环的一个很好的例子是http://scotdoyle.com/python-epoll-howto.html,但很可能没有必要。如果你开始进入套接字编程,你可能想要研究一下

答案 1 :(得分:0)

您无法限制套接字发送速率,唯一的解决方案是限制对发送套接字的调用。 首先,您在此处必须做的是将收到的数据放入容器中(看看to the python Queues),然后,您必须安排发送过程。您可以使用Timer进行此操作。 它的外观可能是:

class Exchange(object):
    def __init__(self):
        #create the queue
        #create the sockets

    def receive_every_seconds_method(self):
        # Here we put the received data into the queue
        self.the_queue.put(self.receiving_socket.recv())

    def send_data_later(self):
        while not self.the_queue.empty():
            self.emission_socket.send(self.the_queue.get())
        # reschedule
        self.schedule()

    def schedule(self, timeout=30):
        self.timer = Timer(timeout, self.send_data_later)
        self.timer.start()

    def run(self):
        self.schedule(30)
        while self.continue_the_job: #this is the stop condition
            self.receive_every_seconds_method()
            time.sleep(1)

这样,您将能够每30秒发送一次数据(如果有数据要发送)

答案 2 :(得分:-1)

go

x:以秒为单位的睡眠时间

相关问题