Recent state of heroic, clear-headed, take advantage of this opportunity, a lot of study, a lot of reading, to see the place before to see again, the Harvest bandits shallow, now two simple small examples dedicated to you:
First a simple UDP broadcast received by the small server, using UDP broadcast, need to pay attention to the use of protocol, has been the most important setting of the socket options, set as the legendary "socket." So_broadcast ", do not need to have a listener, receive client messages using Recvfrom, send messages using sendto:
The code is as follows:
!/usr/bin/env python #coding: Utf-8import socket,tracebackhost = "Port = 51423s =socket.socket (socket.af_inet,socket. SOCK_DGRAM) s.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) s.setsockopt (socket. Sol_socket,socket. so_broadcast,1) S.bind ((Host,port)) While 1:try:message,addr = S.recvfrom (8192) print "Got data from", a DDR s.sendto ("I am Here", addr) except (keyboardinterrupt,systemexit): Raise EXCEPT:TRACEBACK.P Rint_exc (
Broadcast of the client, the client is particularly important to note is the address of the broadcast to write, for <broadcaset>
The code is as follows:
#!/usr/bin/env python #coding: Utf-8import socket,sysdest = (' <broadcast> ', 51423) s = Socket.socket (socket.af_ INET, Socket. SOCK_DGRAM) s.setsockopt (socket. Sol_socket,socket. so_broadcast,1) s.sendto ("Hello", dest) print "Looking for replies:press Ctrl + C to stop" while 1: (buf, address) = S.re Cvfrom (2048) if not Len (BUF): Break print ' revived from%s:%s '% (address, buf)
This article is from the "26-year-old" blog, please be sure to keep this source http://dbbruce.blog.51cto.com/2061658/1568199
python--on the station a simple example of a UDP broadcast