[英]IRC client application, how to use select() in python
嗨,我正在研究從標准輸入讀取數據並將消息發送到無限循環的服務器的網絡應用程序。 對於每個循環,我都有線程,該線程調用函數應執行的操作。 我需要能夠捕獲SIGINT並正確關閉兩個線程。 我的程序卡在兩個讀取功能上。 我想我應該使用select()函數,但是我不知道如何。
def writing_mode():
while 1:
var = raw_input()
# some options with what to do with the var
def listening_mode():
readbuffer = ""
while 1:
readbuffer = readbuffer + s.recv(1024)
temp = string.split(readbuffer, "\r\n")
readbuffer = temp.pop()
for line in temp:
line = string.strip(line)
prefix, command, rest, trailing = parse(line)
# do something with the options u have
s=socket.socket()
try:
s.connect((args.h, args.p))
except Exception, e:
print("Something is wrong with %s:%d, Exception type is:\n%s" % (args.h, args.p, e))
sys.exit()
s.send("NICK AAA\r\n")
s.send("USER AAA AAA AAA AAA\r\n")
thread.start_new_thread(writing_mode)
thread.start_new_thread(listenning_mode)
#main program waiting for signals
我已經通過select()進行非阻塞讀取來解決此問題。
while condition:
# s is socket to read from
# for stdin use sys.stdin instead
ready = select.select([s], [], [], 0)
if ready[0]:
#u can start read
選擇功能僅在有要讀取的內容時才繼續讀取功能。 否則,它將進入while循環,因此條件可以隨時將其停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.