python 线程停止可控

分享代码简介:

  1. 线程:使用原生threading.Thread重写run函数
  2. 停止:使用multiprocessing.Event()监听是否触发停止,触发则停止run内的循环内容
  3. 使用线程建立socket服务端和客户端
  4. 不用安装三方包,window和linux python2环境直接执行

直接贴代码:

  1 # coding: utf-8
  2 # author: elephanyu
  3 import sys
  4 import time
  5 import socket
  6 import traceback
  7 from threading import Thread
  8 from multiprocessing import Event
  9 
 10 def now():
 11     now = time.time()
 12     return '%s.%s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)), int(now % 1 * 1000))
 13 
 14 # socket server
 15 class myserver(Thread):
 16     def __init__(self, host='127.0.0.1', port=5000, time=1):
 17         Thread.__init__(self)
 18         self.host = host
 19         self.port = port
 20         self.time = time
 21         sock = self.get_sock()
 22         if sock:
 23             self.sock = sock
 24         else:
 25             print 'Server get sock err an dieded!'
 26             sys.exit(-1)
 27         self.exit = Event()
 28         print '%s Server init' % now()
 29 
 30     def stop(self):
 31         self.exit.set()
 32 
 33     def get_sock(self):
 34         try:
 35             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 36             sock.settimeout(2)
 37             sock.bind((self.host, self.port))
 38             sock.listen(5)
 39             return sock
 40         except Exception:
 41             print traceback.format_exc()
 42             return None
 43 
 44     def run(self):
 45         while not self.exit.is_set():
 46             try:
 47                 con, addr = self.sock.accept()
 48                 if con:
 49                     con.send('Hello, i am server!')
 50                     time.sleep(self.time)
 51                     recv = con.recv(1024)
 52                     if recv:
 53                         print now() + ' ' + addr[0] + ' server accept: ' + str(recv)
 54             except Exception:
 55                 print traceback.format_exc()
 56         print '%s Server nomal down!' % now()
 57 
 58 # socket client
 59 class myclient(Thread):
 60     def __init__(self, host='127.0.0.1', port=5000):
 61         Thread.__init__(self)
 62         self.host = host
 63         self.port = port
 64         self.exit = Event()
 65         print '%s Client init' % now()
 66 
 67     def stop(self):
 68         self.exit.set()
 69 
 70     def run(self):
 71         while not self.exit.is_set():
 72             try:
 73                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 74                 sock.settimeout(2)
 75                 sock.connect((self.host, self.port))
 76                 sock.send('How are you, server?')
 77                 recv = sock.recv(1024)
 78                 if recv:
 79                     print now() + ' client accept: ' + str(recv)
 80                     sock.close()
 81             except Exception:
 82                 print now() + ' ' + traceback.format_exc()
 83         print '%s Client normal down!' % now()
 84 
 85 if __name__ == '__main__':
 86     host = '127.0.0.1'
 87     port = 5000
 88     speed = 1
 89     rtime = 3
 90     server = myserver(host=host, port=port, time=speed)
 91     client = myclient(host=host, port=port)
 92     server.start()
 93     client.start()
 94     time.sleep(rtime)
 95     client.stop()
 96     server.stop()
 97     while True:
 98         time.sleep(0.5)
 99         s_status = server.is_alive()
100         c_status = client.is_alive()
101         print '%s Check server status: %s' % (now(), s_status)
102         print '%s Check client status: %s' % (now(), c_status)
103         if not s_status and not c_status:
104             break

代码执行结果:

 1 2018-04-20 11:04:20.292 Server init
 2 2018-04-20 11:04:20.292 Client init
 3 2018-04-20 11:04:20.293 client accept: Hello, i am server!
 4 2018-04-20 11:04:21.295 127.0.0.1 server accept: How are you, server?
 5 2018-04-20 11:04:21.295 client accept: Hello, i am server!
 6 2018-04-20 11:04:22.296 127.0.0.1 server accept: How are you, server?
 7 2018-04-20 11:04:22.296 client accept: Hello, i am server!
 8 2018-04-20 11:04:23.298 127.0.0.1 server accept: How are you, server?
 9 2018-04-20 11:04:23.298 Server nomal down!
10 2018-04-20 11:04:23.795 Check server status: False
11 2018-04-20 11:04:23.795 Check client status: True
12 2018-04-20 11:04:24.295 Check server status: False
13 2018-04-20 11:04:24.295 Check client status: True
14 2018-04-20 11:04:24.298 Traceback (most recent call last):
15   File "E:/project/DataIn/TestCode/test/socktest.py", line 76, in run
16     recv = sock.recv(1024)
17 timeout: timed out
18 
19 2018-04-20 11:04:24.298 Client normal down!
20 2018-04-20 11:04:24.795 Check server status: False
21 2018-04-20 11:04:24.795 Check client status: False

猜你喜欢

转载自www.cnblogs.com/elephanyu/p/8889247.html