首页 > 编程 > Python > 正文

Python+Socket实现基于UDP协议的局域网广播功能示例

2020-01-04 16:50:45
字体:
来源:转载
供稿:网友

本文实例讲述了Python+Socket实现基于UDP协议的局域网广播功能。分享给大家供大家参考,具体如下:

服务器端:

# udp_gb_server.py'''服务端(UDP协议局域网广播)'''import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)PORT = 1060network = '<broadcast>'s.sendto('Client broadcast message!'.encode('utf-8'), (network, PORT))

客户端:

# udp_gb_client.py'''客户端(UDP协议局域网广播)'''import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)PORT = 1060s.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协议,局域网,广播

 

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表