簡體   English   中英

python UDP socket客戶端需要發送兩次才能讓服務器接收到包

[英]python UDP socket client need to send twice so that the server can receive the package

我有一個客戶端會向我的服務器發送一些字符串。 但是,我需要發送兩次,以便服務器獲取包裹。 所以對於每一個客戶端想要發送服務器的包,它需要發送兩次。 我不明白為什么會這樣。

我的服務器的監聽代碼:

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()
    received = sock.recvfrom(bufferSize)[0]
    address = sock.recvfrom(bufferSize)[1]

第一個recvfrom將進行第一次讀取。 第二個recvfrom將再次讀取。 瞧:你需要讀兩遍。 相反,您應該進行一次閱讀:

    received, address = socket.recvfrom(bufferSize)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM