I am a newbie to socket programming and I want to send two numbers from client side to server side in UDP and the server will return the product of the two numbers.
When I send the numbers from the client side, there is an error on the server side that "bytes object has no attribute recvfrom".
This is my code
Client side
from socket import socket, AF_INET, SOCK_DGRAM
c = socket(AF_INET, SOCK_DGRAM)
c.connect(('localhost', 11111))
num1 = input('Input a number: ')
num2 = input('Enter a second number: ')
c.sendto(num1.encode('utf-8'), ('localhost', 11111))
c.sendto(num2.encode('utf-8'), ('localhost', 11111))
print(c.recvfrom(1024).decode())
Server side
from socket import socket, AF_INET, SOCK_DGRAM
s = socket(AF_INET, SOCK_DGRAM)
print('Socket created!')
s.bind(('localhost', 11111))
while True:
c, addr = s.recvfrom(1024)
num1 = c.recvfrom(1024)
num2 = c.recvfrom(1024)
print('Received from client having address:', addr)
print('The product of the numbers sent by the client is:', num1*num2)
s.sendto(bytes('***Welcome To The Server***', 'utf-8'))
This is the error that I get:
Exception has occurred: AttributeError
'bytes' object has no attribute 'recvfrom'
File "C:\Users\kryptex\Downloads\Compressed\attachments\udpserv1.py", line 11, in <module>
num1 = c.recvfrom(1024)
CodePudding user response:
c, addr = s.recvfrom(1024)
num1 = c.recvfrom(1024)
num2 = c.recvfrom(1024)
c
are the bytes returned by the s.recvfrom
. You likely meant s.recvfrom
instead of c.recvfrom
. Hint: give your variables more clear and longer names which describe their actual function.
Apart from that it is unclear to me what the intend of c, addr = s.recvfrom(1024)
actually is, since there is no matching send on the client side. I have the feeling that you are confusing TCP and UDP sockets and tried to implement some kind of TCP accept
here, matching the c.connect
on the client side. This is wrong though.