Home >Backend Development >Python Tutorial >Detailed example of Python+Socket implementing LAN broadcast function based on UDP protocol

Detailed example of Python+Socket implementing LAN broadcast function based on UDP protocol

巴扎黑
巴扎黑Original
2017-09-02 13:13:103006browse

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 = &#39;<broadcast>&#39;
s.sendto(&#39;Client broadcast message!&#39;.encode(&#39;utf-8&#39;), (network, PORT))

Client side:


# udp_gb_client.py
&#39;&#39;&#39;客户端(UDP协议局域网广播)&#39;&#39;&#39;
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 1060
s.bind((&#39;&#39;, PORT))
print(&#39;Listening for broadcast at &#39;, s.getsockname())
while True:
  data, address = s.recvfrom(65535)
  print(&#39;Server received from {}:{}&#39;.format(address, data.decode(&#39;utf-8&#39;)))

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn