我尝试通过手动输入从客户端向服务器发送消息,输入了10个限制。它可以在客户端成功运行,但是当我尝试运行服务器时却什么也没显示
这是客户端的代码
import socket
UDP_IP = "localhost"
UDP_PORT = 50026
print ("Destination IP:", UDP_IP)
print ("Destination port:", UDP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range (10):
data = input("Message: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(data)
else :
print("lebih dari 10!!")
s.sendto(data.encode('utf-8'), (UDP_IP, UDP_PORT))
s.close()
这是服务器端的结果和代码
import socket
UDP_IP = "localhost"
UDP_PORT = 50026
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
while True:
data, address = s.recvfrom(1024)
print(data)
print(address)
s.close()
答案 0 :(得分:0)
您的主要问题是您添加到其中的else语句未执行。如果要在接受输入后将限制设置为10,则应在循环后打印该语句。
这是客户端代码:
import socket
UDP_IP = "127.0.0.1" # It is the same as localhost.
UDP_PORT = 50026
print ("Destination IP:", UDP_IP)
print ("Destination port:", UDP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range (10):
data = input("Message: ")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(data)
s.sendto(data.encode('utf-8'), (UDP_IP, UDP_PORT))
print("lebih dari 10!!")
s.close()
编辑:
我不是真的了解您的问题,但据我了解,您想显示服务器的限制。因此,您可以这样做,尝试在服务器上添加循环并仅从客户端地址接收输入,以避免接收到额外的消息。
服务器代码:
import socket
UDP_IP = "127.0.0.1" # It is the same as localhost.
UDP_PORT = 50026
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
x = 0
while True:
data, address = s.recvfrom(1024)
# This block will make sure that the packets you are receiving are from expected address
# The address[0] returns the ip of the packet's address, address is actually = ('the ip address', port)
if address[0] != '127.0.0.1':
continue
# The logic block ends
print(data)
print(address)
x = x + 1 # This shows that one more message is received.
if x == 10:
break # This breaks out of the loop and then the remaining statements will execute ending the program
print("10 messages are received and now the socket is closing.")
s.close()
print("Socket closed")
我已经注释了代码,希望您能理解代码