这篇文章主要介绍了Python+Socket实现基于UDP协议的局域网广播功能,结合实例形式分析了Python+socket实现UDP协议广播的客户端与服务器端功能相关操作技巧,需要的朋友可以参考下
本文实例讲述了Python+Socket实现基于UDP协议的局域网广播功能。分享给大家供大家参考,具体如下:
服务器端:
# udp_gb_server.py '''服务端(UDP协议局域网广播)''' import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) PORT = 1060 network = '<broadcast>' s.sendto('Client broadcast message!'.encode('utf-8'), (network, PORT))
客户端:
# udp_gb_client.py '''客户端(UDP协议局域网广播)''' import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) PORT = 1060 s.bind(('', PORT)) print('Listening for broadcast at ', s.getsockname()) while True: data, address = s.recvfrom(65535) print('Server received from {}:{}'.format(address, data.decode('utf-8')))
运行效果:
以上是实例详解Python+Socket实现基于UDP协议的局域网广播功能的详细内容。更多信息请关注PHP中文网其他相关文章!