0

I'm trying to type-check the commands I want to send to a server from a client. I want to use select so I don't block anything, but if I blatantly ask for input(), I block. So, it seems I should use sys.stdin.readline() instead. However, then there is a disconnect between the commands entered and the type checking I want to do:

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()

Basically, if the client does not recognize the received data as a command, the client assumes it is just a chat message and writes it to stdout accordingly. But, when I get a command like 'GO', I need the client to prompt (or just display a message asking for input so I don't block with input()) the user for command input so I can type-check the command within the same nest. Is this possible without threads?

1
  • This isn't easy. You'll probably have to create a thread to listen for input and have some kind of signal/event system. Commented Dec 15, 2010 at 4:40

1 Answer 1

1

I don't think it is possible to use input() in a non-blocking way without resorting to threads.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.