python强制结束线程,socket通信引用
python2结束线程
import time
import threading
def f():
while 1:
time.sleep(0.1)
print 1
t = threading.Thread(target=f)
t.start()
time.sleep(0.5)
print "Stopping the thread"
threading.Thread._Thread__stop(t)
print "Stopped the thread"
while 1:
time.sleep(0.1)
print t.isAlive()
这种方法最终没有结束线程但是输出的标志位是False,
python3结束线程
#终止线程操作
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
本方法测试成功,并项目应用过
python3测试代码
# -*- coding: UTF-8 -*-
import socket,time,threading # 导入 socket 模块
import inspect
import ctypes
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 创建 socket 对象
s.setblocking(1)
host = socket.gethostname() # 获取本地主机名
port = 8888 # 设置端口
s.bind(('127.0.0.1', port)) # 绑定端口
s.listen(5) # 等待客户端连接
def tcplink(sock,addr):
lastdata = 'off'
print('accept new connection from %s:%s'%addr) #这里addr是一个tuple所以有两个%s
sock.send(b'9')#向客户端返回消息
while True:
data = sock.recv(1024).decode('utf-8')
if not data or data=='exit':
break
else:
print('accept a news :', data) # 从客户端接受消息,最大1024字节
sock.close() #关闭套接字
print(b'connection from :',addr,b'closed')
class myThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("start test")
data = 1
while True:
print(data)
data += 1
time.sleep(3)
#终止线程操作
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
def Datacheck(data):
print(data)
sock.send(data.encode('utf-8'))
while True:
print('waiting for connection')
A = myThread()
A.start()
try:
sock,addr = s.accept() # 建立客户端连接
stop_thread(A)
B = threading.Thread(target=tcplink(sock,addr))
B.start()
except:
print("ERROR CLOSED")
continue
# -*- coding: UTF-8 -*-
import socket
host = socket.gethostname() # 获取本地主机名
s = socket.socket()
s.connect(('127.0.0.1',8888))
while True:
try:
print(s.recv(1024).decode('utf-8'))
data = input("raw_input:") #所有输入都当成字符串
s.send(data.encode('utf-8')) #向服务器传递消息
if data == 'exit':
break
except:
print("ERROR CLOSED")
break
s.close()