[英]How do I make a UDP server constantly receive datagrams in Python
I am creating a server and client socket in Python.我正在 Python 中创建服务器和客户端套接字。 I have managed to send datagrams between them but I need to set the server to constantly listen for UDP messages but I can't work out how.
我已经设法在它们之间发送数据报,但我需要将服务器设置为不断监听 UDP 消息,但我不知道如何。 I have seen the serve_forever() function but when I enter it, it tells me that 'NameError: name 'serve_forever' is not defined.
我见过 serve_forever() function 但是当我输入它时,它告诉我'NameError:名称'serve_forever'没有定义。 Do I need to import something or have I missed something completely.
我需要导入一些东西还是我完全错过了一些东西。 I am quite new to this so wasn't sure if I needed to add anything else in. Here is the beginning of the code:
我对此很陌生,所以不确定是否需要添加其他任何内容。这是代码的开头:
import socket
serverSocket = socket.socket(socket.AF_INET , socket.SOCK_DGRAM)
UDP_IP = "localhost"
UDP_PORT = 6842
address = ("localhost" , 6842)
serverSocket.bind(address)
serve_forever()
print ("Waiting for client...")
I suspect you can replace serve_forever()
with something this:我怀疑您可以用以下内容替换
serve_forever()
:
while True:
data = serverSocket.recv(65535)
print("Received a UDP packet containing %i bytes of data" % len(data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.