运行时错误无法启动新线程

时间:2018-06-07 18:47:12

标签: python multithreading python-3.x tcp python-multithreading

我正在尝试检查一个端口上是否有数据可用。如果这是可用的那么一条消息"是"应该被送到另一个港口和"没有"如果没有数据。 客户端正在连接到该端口,其中"是"或"不"来了。我运行脚本,每件事看起来都很好。但是一小时后我得到了错误: 运行时错误无法启动新线程。线程11中的异常: 回溯<最近一次调用last:文件threading.py第914行在boot strap-inner中。

我是python的新手,我真的不明白发生了什么。我的代码包含许多线程,因为我正在检查来自10个端口的数据并发送"是"或"不"消息到其他10个端口。 这是我的1端口代码的一部分:

    import time
import socket
import threading
from threading import Thread
import select

#-----------------------------------Server --------------------------
s = socket.socket(socket.AF_INET) #Socket
h = '127.0.0.1' #Host where data coming from
p = 14201 #Port
halarm = "127.0.0.1" # A port will be opened to send availabilty status
palarm = 14202 # Port
def Server ():
    while True:
        try:
            time.sleep(0.1)
            s.connect((h, p))
        except socket.error:
            pass

#-----------------------------------Server/Client -------------------------------
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((halarm, palarm)) # Bind to the Port where
sock.listen(1)        
def func(conn): # Server-Client Function 
    while True:
        try:
            global s
            Timeout = select.select([s], [], [], 5)# Timeout in seconds
            connected = True
            while True:

                try:
                    if Timeout[0]:
                        conn.send(bytes("yes", "utf-8"))
                        time.sleep(3)
                    else:
                        conn.send(bytes("no", "utf-8"))
                        time.sleep(3)
                    newConnection= False
                    while not newConnection:
                        try:
                            s = socket.socket(socket.AF_INET)
                            s.connect((h, p))
                            Timeout = select.select([s], [], [], 5)# Timeout in seconds
                            newConnection= True
                        except socket.error:
                            conn.send(bytes("Port is closed", "utf-8"))                            
                            time.sleep(3)
                            pass
                except socket.error:
                    pass
        except:
            pass
def connThread():
    while True:
        conn, addr = sock.accept()
        time.sleep(0.1)
        Thread(target = func, args=(conn,)).start()

if __name__ == '__main__':
    Thread(target = Server).start()
    Thread(target = connThread).start()

我该如何解决这个问题?我感谢你的帮助。

0 个答案:

没有答案