Handle multiple requests with select

前端 未结 2 1571
悲&欢浪女
悲&欢浪女 2020-12-07 04:28

currently I am working on a chat server/client project. I am struggling with handling multiple requests with select, my server script uses the select module but the client s

2条回答
  •  天命终不由人
    2020-12-07 05:19

    my server script uses the select module but the client script doesn't.

    A solution is to use select also in the client. On Windows unfortunately select does not handle sys.stdin, but we can use the timeout argument to poll the keyboard.

    import socket
    import select
    import msvcrt
    client_socket = socket.socket()
    client_socket.connect(("localhost", 2855))
    msg = ""
    while True:
        ready = select.select([client_socket], [], [], .1)
        if client_socket in ready[0]:
            data = client_socket.recv(1024)
            print data, ' '*(len(msg)-len(data))
            print msg,
        if msvcrt.kbhit():
            key = msvcrt.getche()
            if key == '\r': # Enter key
                if msg == "quit":
                    break
                client_socket.send(msg)
                msg = ""
                print
            else:
                msg = msg + "" + key
    client_socket.close()
    

提交回复
热议问题