python: how to send packets in multi thread and th

2019-01-11 21:00发布

I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python.

Here is my code so far:

#! /usr/bin/env python                                                          

import socket
import thread
import time

IP = "192.168.0.2"
PADDING = "a" * 1000 #assume the MTU is slighly above 1000
DATA = PADDING + "this is sentence number = "
PORT = 14444
killed = False
test_time = 60 #60 seconds of testing

def send_data():
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((IP, PORT))
  count = 1
  starttime = time.clock()
  while elapsed < test_time:
    sent = s.send(DATA + str(count) + "\n")
    if sent == 0: break # assume that if nothing is sent -> connection died
    count = count+1
    elapsed = time.clock() - starttime
    if killed:
      break
  s.close()
  print str(count) + " has been sent"

print "to quit type quit"
thread.start_new_thread(send_data, ())

while True:
  var = raw_input("Enter something: ")
  if var == "quit":
    killed = True

Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?

Thanks

7条回答
小情绪 Triste *
2楼-- · 2019-01-11 21:48

Ensure that the "quit" is working correctly and add a small print to test that the input is working.

if var == "quit":
 print "Hey we got quit"
查看更多
登录 后发表回答