使用 kbhit 的 Python 套接字线程

标签 python multithreading sockets keypress

我已经不知道如何在单击需要按下的指定键后,python 中的 msvcrt.kbhit() 打印出数据。看起来 while 循环需要再次循环才能打印出我想要的输出。有人可以帮帮我吗。这是我的代码:

def run(self):
    global state
    print "\nClient connection received!\n"
    self.channel.send("Status: Server connection received")
    while 1:
        ctr = 1
        while 1:
            self.clientmess = self.channel.recv(Buffer)
            if msvcrt.kbhit():
                if msvcrt.getch() == 's':
                    print "stop"
                    break
    #the codes belo is what i will want for self.clientmess will be so its not necessary I think to put

最佳答案

大多数时候,您的程序会阻塞在 recv 调用中,因此在接收到一些数据之前,它不会执行 kbhit+getch。如果您需要立即处理键盘输入,您可能需要使套接字成为非阻塞并在循环中轮询套接字和键盘,在出现时处理来自它们的数据。

关于使用 kbhit 的 Python 套接字线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15526484/

相关文章:

python - Sklearn 决策树 - 同时使用稀疏矩阵和其他特征

java - 如何让对象在自己的线程中与其他代码同时运行其命令

python - 检查路径是否是 Python 2.7 中的套接字

python - 具有多个列表的列表理解中的 If 语句

python - "too many resources for launch"的解释

在 R 中使用多线程运行 shell 脚本

c - C语言的套接字编程,服务器代码出错

C++ 通过套接字发送字符串

python - 为什么内联交换返回意外结果?

c - 通过管道从多个子进程写入父进程