python超时问题

在写程序的时候会在while循环中卡死,或者在界面中卡死等问题。这一切都可以通过超时函数来解决,让你的程序跳出死循环。

下面将通过客服端和服务端给出一个简单的例子:包含了多线程、修饰函数、超时问题socket通信等。

QApplication.processEvents()可以刷新解决pyqt界面卡顿。

服务端,一直跑不断线,等你来连接:

#!usr/bin/python3
# -*- coding:utf-8 -*-
# author:SingWeek


import socket
import random
import threading
import inspect
import ctypes

def _async_raise(tid, exctype):
    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 mytimeout(ctime):
    """
    修饰函数之超时函数
    :param ctime:超时时间
    :return:
    """
    ctime=ctime
    def timeout(func):
        def call():
            t=threading.Thread(target=func)
            t.setDaemon(True)
            t.start()
            t.join(ctime)
            # print("超时!")
        return call
    return timeout

class Test():
    def __init__(self):
        bind_ip = "127.0.0.1"
        bind_port = 8080  #这里绑定的端口必须得和客户端访问的端口是一致的
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((bind_ip, bind_port))
        self.server.listen(9)
        self.client=''
        self.addr=''
        self.flags=False
    """mytimeout修饰的函数自定义写的是不能向里面传递参数,所以通过Class self来实现参数改变值的传递"""
    def Out(self):
        @mytimeout(5)#设定5秒超时
        def Accept():
            self.client=''
            self.addr=''
            self.client, self.addr = self.server.accept()
        Accept()
        return self.client,self.addr


def handle_client(client_socket,data):
    request = client_socket.recv(1024)
    print("Server Received:%s" % request.decode())
    tmp="服务端发送数据:%s"%data
    client_socket.send(tmp.encode())
    client_socket.close()

recv=Test()
data=[1,2,3,4,5,6,7,8,9,10]
flags=True
while True:
    if flags==True:
        print("----------------------------")
        client, addr = recv.Out()
        if client!='' and addr!='':
            # print("[*]Accepted connection from:%s:%d" % (addr[0], addr[1]))
            client_handler = threading.Thread(target = handle_client, args = (client,data[random.randint(0,9)]))
            client_handler.start()
        else:
            print(client, addr)
    else:
        pass

 

客户端,一直跑,不断线,等你上线:

#!usr/bin/python3
# -*- coding:utf-8 -*-
# author:SingWeek

target_host = "127.0.0.1"
target_port = 8080
import socket
import time
def Wifi_Send_Data(target_host = "127.0.0.1",target_port = 8080,data=''):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((target_host, target_port))
    client.send(data.encode())
    response = client.recv(4096).decode()
    print(response)
    time.sleep(2)
while True:
    try:
        Wifi_Send_Data(data="测试时间%s"%time.time())
    except Exception as e:
        print(e)

 

你可能感兴趣的:(Python,超时,python超时,socket通信)