繁体   English   中英

无法从客户端读取消息:UDP python 3

[英]Cannot read message from client : UDP python 3

我试图通过手动输入从客户端向服务器发送消息,输入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()

当我运行程序时,没有任何事情发生。 这是正在运行的程序 结果

你的主要问题是你在那里添加的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")

我已经对代码进行了评论,所以我希望您能理解代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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