我是套接字編程的新手,我想在 UDP 中從客戶端向服務器端發送兩個數字,服務器將回傳這兩個數字的乘積。
當我從客戶端發送數字時,服務器端出現“位元組物件沒有屬性recvfrom”的錯誤。
這是我的代碼
客戶端
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())
服務器端
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'))
這是我得到的錯誤:
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)
uj5u.com熱心網友回復:
c, addr = s.recvfrom(1024)
num1 = c.recvfrom(1024)
num2 = c.recvfrom(1024)
c是回傳的位元組s.recvfrom。您可能的意思是s.recvfrom而不是c.recvfrom. 提示:給你的變數更清晰和更長的名稱來描述它們的實際功能。
除此之外,我不清楚c, addr = s.recvfrom(1024)實際的意圖是什么,因為客戶端沒有匹配的發送。我感覺您混淆了 TCP 和 UDP 套接字,并試圖在這里實作某種 TCP accept,與客戶端匹配c.connect。這是錯誤的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515794.html
