1. 程式人生 > >python UDP 區域網廣播訊息

python UDP 區域網廣播訊息

server端:

# -*- coding: utf-8 -*-
import ctypes
import socket

# ipv4        SOCK_DGRAM指定了這個Socket的型別是UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# 繫結 客戶埠和地址:
s.bind(('', 9999))
print 'Bind UDP on 9999...'
while True:
    # 接收資料 自動阻塞 等待客戶端請求:
    data, addr = s.recvfrom(1024)
    message = 'Received from %s:%s.' % (addr, data)
    print message
    ctypes.windll.user32.MessageBoxA(0, data.decode("utf-8").encode('gb2312'), u' 資訊'.encode('gb2312'), 0)

client端

# -*- coding: utf-8 -*-

import socket

'''
客戶端使用UDP時,首先仍然建立基於UDP的Socket,然後,不需要呼叫connect(),直接通過sendto()給伺服器發資料:
'''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 9999
network = '<broadcast>'
# 傳送資料:
s.sendto(u"有新檔案到達,請登入http://192.168.1.2:8080檢視".encode("utf-8"), (network, PORT))

s.close()

python指令碼打包成exe,可以使用PyInstaller

pip install PyInstaller
pyinstaller xxx.py