python--on the station a simple example of a UDP broadcast

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.