use*_*790 5 python sockets multithreading timer packet
我有个问题.我想使用python向一些主机发送连续的字节流一段时间(假设1分钟).
到目前为止,这是我的代码:
#! /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
Run Code Online (Sandbox Code Playgroud)
几乎没有问题,除了每次轮询时间之外,有没有更好的方法让线程在60秒后死亡?当我运行这个程序时,它正确地发送字节,但是当我键入退出时,另一个线程不会死,即使我设置了var killed = True.我想知道为什么会这样?var杀死的范围应该到达另一个线程吗?
谢谢
我推荐使用线程模块.更有利的是使用InterruptableThread来终止线程.您不必使用标志来终止您的线程,但如果您从父线程调用此线程上的terminate(),则会发生异常.你可以处理异常.
import threading, ctypes
class InterruptableThread(threading.Thread):
@classmethod
def _async_raise(cls, tid, excobj):
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError("PyThreadState_SetAsyncExc failed")
def raise_exc(self, excobj):
assert self.isAlive(), "thread must be started"
for tid, tobj in threading._active.items():
if tobj is self:
self._async_raise(tid, excobj)
return
def terminate(self):
self.raise_exc(SystemExit)
Run Code Online (Sandbox Code Playgroud)
编辑: 您可以使用另一个等待1分钟然后杀死其他线程的线程重写您的代码
def send_data:
IP = ...
# other vars
...
s = socket.socket(.....)
# no killed checking
# no time checking
# just do your work here
...
s.close()
my_thread = InterruptableThread(target=send_data)
my_thread.start()
def one_minute_kill(who):
time.sleep(60)
who.terminate()
killer_thread = InterruptableThread(target=one_minute_kill, args=[my_thread])
killer.start()
print "to quit type quit"
while my_thread.isAlive():
if raw_input("Enter something: ") == "quit":
my_thread.terminate()
Run Code Online (Sandbox Code Playgroud)
确保“退出”正常工作,并添加一个小字体来测试输入是否正常工作。
if var == "quit":
print "Hey we got quit"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5645 次 |
| 最近记录: |