I'm making a packet generator and it's crucial to be able to send packets as steadily and as accurately as possible. The problem I'm having is that I send the packets using a while loop with time.sleep that is supposed to loop hundreds times/second, but since it takes additional and varying time to go through the loop it's hard to set a right sleeping time.
Here is the code I'm using:
while status == "1":
try:
s.send(message)
data = s.recv(1500)
status = self.clientstatus
time.sleep(1.0 / (speed*100))
except:
status = "0"
EDIT:
Here is a working solution that I used
def clientstart(self):
self.sch = sched.scheduler(time.time, time.sleep)
self.next_time = time.time()
self.sch.enterabs(self.next_time, 0, self.oneround, ())
self.reset.emit()
time.sleep(0.03)
n = 0
targetip = self.entry1.text()
host = targetip
port = 5001
speed = int(self.entry2.text())
self.delay = 1.0 / (speed*100)
if targetip:
self.s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
try:
self.s.connect((host,port))
except:
self.err1.emit(1)
n = n+1
openfile = open('1024')
self.message = openfile.read()
self.clientstatus = "1"
status = self.clientstatus
self.buttonswitch("2")
n = n+1
self.nn = 1
t = threading.Thread(target = self.temp)
t.setDaemon(True)
t.start()
self.err1.emit(2)
self.sch.run()
if n == 1:
self.err1.emit(4)
elif n == 4:
self.err1.emit(0)
self.s.close()
self.buttonswitch("3")
else:
self.err1.emit(3)
def oneround(self):
try:
self.s.send(self.message)
status = self.clientstatus
self.nn += 1
if status == '1':
self.next_time += self.delay
self.sch.enterabs(self.next_time, 0, self.oneround, ())
except:
pass
using self with socket might cause some problems in the future though