OSError: [Errno 22] invalid argument socket python socket

OSError: [Errno 22] invalid argument socket python socket

我有一些使用 UDP 套接字的应用程序。每个应用程序都可以发送和接收日期。
在接收数据的应用程序中,代码如下:
接收器应用程序:

UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
bufferSize= 1024
EnginePort=2000


def ReceiveSocket():
    global UDPSocket
    global AddressPort
    global bufferSize
    AddressPort   = ("127.0.0.2", EnginePort)
    # Bind to address and ip
    UDPSocket.bind(AddressPort)
    print("UDP server up and listening")
    bytesAddressPair = UDPSocket.recvfrom(bufferSize)
    message = pickle.loads(bytesAddressPair[0])
    address = bytesAddressPair[1]
    clientMsg = "Message from Client:{}".format(message)
    clientIP  = "Client IP Address:{}".format(address)
    print(clientMsg)
    print(clientIP)


while True:
    ReceiveSocket()

正在发送一条简单的消息:

import socket
import pickle
UDP_IP = "127.0.0.2"
UDP_PORT = 2000
MESSAGE = "Hello, World!"

print ("UDP target IP:", UDP_IP)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.sendto(pickle.dumps(MESSAGE), (UDP_IP, UDP_PORT))

接收数据时报错:
接收器输出:

Message from Client:Hello, World!
Client IP Address:('127.0.0.2', 2003)
Traceback (most recent call last):
  File "/home/pi/RoomServerTestApps/Engine.py", line 88, in <module>
    ReceiveSocket()
  File "/home/pi/RoomServerTestApps/Engine.py", line 29, in ReceiveSocket
    UDPSocket.bind(AddressPort)
OSError: [Errno 22] Invalid argument

但是当 ReceiveSocket()while true() 之外时,应用程序运行良好。
请帮我解决这个问题。
谢谢。

让 bind() 脱离循环。您已经在第一个 运行 绑定到端口,这就是第二个 + 运行 失败的原因。

AddressPort   = ("127.0.0.2", EnginePort)
UDPSocket.bind(AddressPort)
def ReceiveSocket():
...