Created
September 9, 2014 12:46
-
-
Save anonymous/f7c4399afd42c4f36fea to your computer and use it in GitHub Desktop.
Python 网络编程基础中的那个广播程序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import socket, sys | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) | |
MAX = 65535 | |
PORT = 1060 | |
if 2 <= len(sys.argv) <= 3 and sys.argv[1] == 'server': | |
s.bind(('', PORT)) | |
print('Listening for broadcasts at', s.getsockname()) | |
while True: | |
data, address = s.recvfrom(MAX) | |
print('The client at {0} says: {1}'.format(address, data.decode())) | |
elif len(sys.argv) == 3 and sys.argv[1] == 'client': | |
network = sys.argv[2] | |
s.sendto('Broadcast message!'.encode(), (network, PORT)) | |
else: | |
print('usage: udp_broadcast.py server', sys.stderr) | |
print('or: udp_broadcast.py client <host>', sys.stderr) | |
sys.exit(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment