Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

python socket object accept time out

Question: Is there some sort of time out or interrupt to the socket.accept() function in python?


Info:

I have a program that has a child thread bound to a port and constantly accepting and tending and passing them to a queue for the main thread. Right now I'm trying to get the child thread to interrupt so it can deconstruct appropriately. I think it is possible for me to just simply stop the child thread and have the parent deconstruct the child, but there are other times where I want to be able to return early form accept so I just decided that would be the most useful approach.

So, is there a way that I can have a time out or cancel the accept method so the thread can return w/o having something connect to it first?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use settimeout() as in this example:

import socket

tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.settimeout(0.2) # timeout for listening
tcpServer.bind(('0.0.0.0', 10000)) # IP and PORT
tcpServer.listen(1)

stopped = False
while not stopped:
  try: 
    (conn, (ip, port)) = tcpServer.accept() 
  except socket.timeout:
    pass
  except:
    raise
  else:
    # work with the connection, create a thread etc.
    ...

The loop will run until stopped is set to true and then exit after (at most) the timeout you have set. (In my application I pass the connection handle to a newly created thread and continue the loop in order to be able to accept further simultaneous connections.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...