0
我想鍵入檢查我想從客戶端發送到服務器的命令。我想使用選擇,所以我不阻止任何東西,但如果我公然要求input()
,我阻止。所以,我應該使用sys.stdin.readline()
來代替。然而,再有就是我想要做輸入的命令和類型檢查之間的脫節:如何在python3中提示用戶輸入而不阻塞?
while not self.flag:
sock_read, sock_write, sock_except = \
select.select([sys.stdin, self.client], [], [])
for sock in sock_read:
if sock == sys.stdin:
data = sys.stdin.readline().strip()
if data:
self.client.send(data.encode('utf_8'))
elif sock == self.client:
data = sock.recv(bufsize)
if data.decode('utf_8') is '': # server closed connection
print("Lost connection to server, shutting down...")
self.flag = True
break
else: # process data '\n' delimited
readbuf += data
while b'\n' in readbuf:
msg,readbuf = readbuf.split(b'\n', 1) # separate by \n
msg = msg.decode('utf_8')
msg.strip('\n')
# make below into a function
# got data from server
if msg == 'BEGIN':
self.playstarted = True
elif msg == 'GO':
#command = input("Your turn: ")
# typecheck command, something like
# while is_not_valid_command():
# keep asking for input
print("You",command)
command += '\n' # delimiter
sock.send(command.encode('utf_8'))
else:
sys.stdout.write(msg + "\n")
sys.stdout.flush()
基本上,如果客戶端不識別接收到的數據作爲命令,客戶端會假定它只是一個聊天消息並相應地將其寫入標準輸出。但是,當我得到像'GO'
這樣的命令時,我需要客戶端提示(或只是顯示一條消息,要求輸入,因此我不會阻止input()
)用戶輸入命令,因此我可以在同一個類型中檢查命令巢。這可能沒有線程?
這並不容易。你可能不得不創建一個線程來監聽輸入並且有某種信號/事件系統。 – Falmarri 2010-12-15 04:40:20