程序卡在 accept 语句

Program getting stuck at accept statement

我刚刚发布了我的程序的一部分。第一次我 运行 程序时,我可以从客户端提供输入,服务器通过接受,但是当程序 运行s 进行第二个循环时,它会卡在 mysocket.accept 中。使套接字成为非阻塞并不能解决问题 this.Does 有人知道如何清除这个错误吗?

class Memory(threading.Thread):

    def __init__ (self):
        threading.Thread.__init__ (self)

    def run(self):
        global data_queue
        while True:
            sleep(0.1)
            mysock.listen(5)
            print "waiting for data"
            conn, addr = mysock.accept()
            print "received data from client"
            data = conn.recv(1000)
            data_queue.put(data)

class Execute(threading.Thread):

    def __init__ (self):
        threading.Thread.__init__ (self)

    def run(self):
        global data_queue
        while True:

            if not data_queue.empty():
                data = data_queue.get()
                if not data:
                    break
                if data == b'on':
                    print "on"
                    gpio.output(4,True)
                if data == b'off':
                    print "off"
                    gpio.output(4,False)

客户端程序:

try:
    a = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print("Failed to create socket")
    sys.exit()

a.connect(('127.0.0.1', 1236))

while True:
    print "1.ON 2.OFF"
    choice = input('Enter your choice')
    if choice == 1:
        try:
            a.sendall(b"on")
        except socket.error:
            print("Failed to send")
            sys.exit()

    if choice == 2:
        try:
            a.sendall(b"off")
        except socket.error:
            print("Failed to send")
            sys.exit()

ms.close()

我相信您在内存线程中想要的是:

def __init__ (self):
    threading.Thread.__init__ (self)

def run(self):
    global data_queue
    mysock.listen(5)
    print "waiting for data"
    while True:
        sleep(0.1)
        conn, addr = mysock.accept()
        print "received connection from client"
        self.talk_to_client(conn)

def talk_to_client(self, conn):
    data = conn.recv(1000)
    while data != 'quit':
        reply = prepare_reply_to_client(data)
        data_queue.put(reply)
    conn.close()     # if we're done with this connection

注意我是如何将 listen 移到 while 循环之上的,所以它只发生一次。您的问题是您对 listen() 的第二次调用与第一次调用冲突。你应该只打电话听一次。随后的接受将克隆侦听套接字并将其用于连接。完成连接后关闭该连接,但您的监听器会继续等待新连接。

这是 python 文档中的典型示例:https://docs.python.org/2/library/socket.html#example

已更新:通过编写方法 talk_to_client(conn)

添加与客户端扩展交互的示例