0
クライアントからサーバーに送信するコマンドをタイプチェックしようとしています。私は何もブロックしないようにselectを使用したいですが、ぼんやりと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