python UDP套接字客户端需要发送两次,以便服务器可以接收包

python UDP套接字客户端需要发送两次,以便服务器可以接收包,python,sockets,Python,Sockets,我有一个客户端将发送一些字符串到我的服务器。但是,我需要发送两次,以便服务器获得包。因此,对于每个客户端想要发送服务器的包,它需要发送两次。我不明白为什么会这样 我的服务器执行侦听的代码: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) myIp = "0x2A" myPort = 2222 targetPort = 0 myAddress = ("localhost",myPort) bufferSize = 1024 def

我有一个客户端将发送一些字符串到我的服务器。但是,我需要发送两次,以便服务器获得包。因此,对于每个客户端想要发送服务器的包,它需要发送两次。我不明白为什么会这样

我的服务器执行侦听的代码:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
myIp = "0x2A"
myPort = 2222
targetPort = 0
myAddress = ("localhost",myPort)
bufferSize = 1024

def listen():

    print('starting up on {} port {}'.format(*myAddress))
    sock.bind(myAddress)
    # sock.listen(1)
    print("waiting for message")
    # connection, client_address = sock.accept()
    while True:

        received = sock.recvfrom(bufferSize)[0]
        address = sock.recvfrom(bufferSize)[1]
        received = json.loads(received.decode()) 
        source = received.get("source")
        destination = received.get("destination")
        length = received.get("length")
        message = received.get("message")
        protocol = received.get("protocol")

        print("the source is: " + source)
        if destination == myIp:
            print("the message is: " + message)
            print('sending back to sender...')
            sock.sendto(message.encode(),address)

            if protocol == 0:
                print("protocol is: " + str(protocol))
            elif protocol == 1:
                print("protocol is: " + str(protocol))
                print("write data to log file....")
                f = open("log.txt","w")
                f.write(message)
                print('done!')

            elif protocol == 2:
                print("protocol is: " + str(protocol))
                # sock.close()
                print("exit")
                sock.close()
                sys.exit()
        else:
            print("this is not my package: \n" + "destination Ip is: " + destination + "\n my Ip is: " + myIp)

        if not received:
            break
我的客户进行发送的代码:

def send():
    try:
        sock.sendto(message.encode(),serverAddress)
        print("message: " + message +  " is sent")
    finally:
        print('closing socket')
        sock.close()
第一个recvfrom将进行第一次读取。第二个recvfrom将进行另一次读取。瞧,你需要两次阅读。相反,您应该进行一次阅读:

    received, address = socket.recvfrom(bufferSize)
    received, address = socket.recvfrom(bufferSize)