python强制结束线程,socket中的应用

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测试代码

server.py

# -*- 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

client.py

# -*- 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()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值