使用UDP套接字在python中发送连续数据

时间:2019-07-09 11:15:57

标签: python sockets udp

我有两个文件,sendreceive,它们通过UDP套接字传输数据。我在send文件中发送连续数据;但是receive获得第一个数据。
发送文件

UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
AddressPort   = ("127.0.0.2", LocalReadPort)
bufferSize          = 1024

def SendSocket(Packet,Port):
    global UDPSocket
    global bufferSize
    print('Connecting...')
    msgFromOrigin       = Packet
    AddressPort   = ("127.0.0.2", Port)
    # Create a UDP socket at client side
    UDPSocket.sendto(Packet, AddressPort)
    msgFromDestination= UDPSocket.recvfrom(bufferSize)
    msg = "Message from Server {}".format(pickle.loads(msgFromDestination[0]))
    print(msg)

def HD():
    for i in range (0,3):
        SendSocket(pickle.dumps(i),EnginePort)

while True:
    HD()

接收文件:

UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
AddressPort = ("127.0.0.2", EnginePort)
bufferSize = 1024
UDPSocket.bind(AddressPort)
print("UDP server up and listening")

def ReceiveSocket():
    global UDPSocket
    global AddressPort
    global bufferSize

    # Bind to address and ip
    bytesAddressPair = UDPSocket.recvfrom(bufferSize)
    print('1')
    message = pickle.loads(bytesAddressPair[0])
    address = bytesAddressPair[1]
    clientMsg = "Message from Client:{}".format(message)
    clientIP  = "Client IP Address:{}".format(address)
    print(clientMsg)
    print(clientIP)

输出

1
Message from Client: 0
Client IP Address:('127.0.0.1', 57742)

您能帮我吗?
谢谢。

0 个答案:

没有答案