Home >Backend Development >Python Tutorial >Detailed example of Python+Socket implementing LAN broadcast function based on UDP protocol
This article mainly introduces Python+Socket to implement the LAN broadcast function based on the UDP protocol. It analyzes the related operation skills of the client and server-side functions of Python+socket to implement UDP protocol broadcast in the form of examples. Friends in need can refer to the following
The example of this article describes the implementation of LAN broadcast function based on UDP protocol by Python+Socket. Share it with everyone for your reference, the details are as follows:
Server side:
##
# 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))Client side:
# 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')))Operation effect:
The above is the detailed content of Detailed example of Python+Socket implementing LAN broadcast function based on UDP protocol. For more information, please follow other related articles on the PHP Chinese website!