OSError:[Errno 22]无效的参数套接字python套接字

时间:2019-07-09 07:52:22

标签: python sockets udp

我有一些使用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()之外时,应用程序运行良好。
请帮我解决这个问题。
谢谢。

1 个答案:

答案 0 :(得分:0)

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

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