# 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 = ''
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脚本打包成exe,可以使用PyInstaller
pip install PyInstaller
pyinstaller xxx.py
可实现局域网聊天,局域网的自动发现