简体   繁体   English

使用两个端口的Python 3线程

[英]Python 3 Threading Using Two Ports

i am working on a basic python program to get used to threading and networking and i have become a little unstuck at one section of my code. 我正在研究一个基本的python程序,以习惯于线程化和联网,并且我对代码的某一部分有些不了解。

what i have is: 我所拥有的是:

#make a socket and loop to obtain connections 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ads = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(("127.0.0.1" , 4000))
ads.bind(("127.0.0.1" , 4001))

s.listen(10)
ads.listen(1)

socks = [s,ads]
connections = [] # list of connections 

while True:
    if ads:
        (c,a) = ads.accept()
        t = threading.Thread(target = admin_client, args = ())
        t.start()
    elif :   
        (c,a) = s.accept()
        connections.append(c)
        t = threading.Thread(target = handle_client, args = (c,a))
        t.start()

What i was hoping to happen was when the ads port was accessed it would assign it to the admin_client method which it seems to perform but it will just do nothing if anything connects on the s port. 我希望发生的是访问广告端口时,它将把它分配给似乎执行的admin_client方法,但是如果s端口上有连接,它将什么都不做。

Does anyone have a solution for this so both clients will connect with no issues? 有没有人对此有解决方案,所以两个客户端都不会出现问题?

if ads: is always True. if ads:始终为True。 You need to use select . 您需要使用select Since if ads: is always True you drop into (c,a) = ads.accept() which waits for someone to connect to the ads port. 因为if ads:始终为True,那么您将陷入(c,a) = ads.accept() ,它等待有人连接到广告端口。

Something like (untested): 像(未经测试的):

r,w,x = select.select(socks,[],[])
if ads in r:
     ...
elif s in r:
     ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM