简体   繁体   中英

Send and receive to/from a UDP socket python3.4

i have these lines of code for sending and receving from a UDP socket in python3.4, in which i want to send a file from a user to the other. This is the server side code:

...
data = file.read(1024)
n = int(fileSize / 1024) + 1
for i in range(n):
    if(self.sock.sendto(data.encode(), ('127.0.0.1',int(self.nextUserPort)))):
        print ("Sending ...")
        data = file.read(1024)
print ("File has been Sent Completely!!!")
self.sock.sendto("END#".encode(), ('127.0.0.1',int(self.nextUserPort)))

And this is the client side code:

....
d = self.sock.recvfrom(1024)
data = d[0].decode()
addr = d[1]
try:
    while (data.strip().find("END#") != 0) :
        file.write(data.decode())
        time1 = time.time()
        data, addr = self.sock.recvfrom(1024)
        time2 = time.time()
        print ("download speed is "+ str(1.0/(time2-time1))+" kbps")
    print ("File Downloaded Completely!!!!!")
except socket.timeout :
    file.close()
    self.sock.close()

But when i run the code i get the below error for the line f(self.sock.sendto(data.encode(), ('127.0.0.1',int(self.nextUserPort)))) :

AttributeError: 'bytes' object has no attribute 'encode'

And when i remove the encode i get another error that when i searched it i got that i must encode it in python3.4 .

The exception is telling you what the problem is:

AttributeError: 'bytes' object has no attribute 'encode'

And as it happens you want to send bytes, so no need to convert anything in this line.

"END#".encode() can be directly written as b"END#" .

Unrelated to your question: You might want use a TCP socket or give the transfer some logic to cope with reordered, lost and duplicated packages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM