如何在udp广播中将数据从服务器发送到客户端

时间:2018-07-12 06:44:19

标签: python udp

我用python创建了udp代码,我想从其他设备获取数据,但是我什么也没得到,我也关闭了防火墙,但无法正常工作。 服务器代码:

#!/usr/bin/env python
# -*- coding:utf8 -*-
#udp server
import socket, sys

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server_address = ('', 9434) #綁定同個域名下的所有地址
sock.bind(server_address)

response = 'pfg_ip_response_serv'

while True:
    data, address = sock.recvfrom(4096)
    data = str(data.decode('UTF-8'))

    if data == 'pfg_ip_broadcast_cl':
        sent = sock.sendto(response.encode(), address)
    else:
        print("Not message")

sock.close()

客户代码:

#!/usr/bin/env python
# -*- coding:utf8 -*-
#udp client
import socket, sys, time

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.settimeout(5)

server_address = ('255.255.255.255', 9434)
message = 'pfg_ip_broadcast_cl'

try:
    while True:
        # Send data
        print('sending: ' + message)
        sent = sock.sendto(message.encode(), server_address)

        print('waiting to receive...')
        data, server = sock.recvfrom(4096)
        if data.decode('UTF-8') == 'pfg_ip_response_serv':
            print('Received confirmation')
            print('Server ip: ' + str(server[0]))
            break
        else:
            print('Verification failed')

        print('Trying again...')
        time.sleep(3)

finally:    
    sock.close()

然后,当我将“ 255.255.255.255”更改为设备的IP时,它可以工作。谢谢,我不知道该怎么解决。

0 个答案:

没有答案