使用PYTHON接收多播数据的代码

518次阅读  |  发布于5年以前

首先声明,这不是我写的,而是我找到的,但是别人写的相当好。

复制代码 代码如下:

UDP multicast examples, Hugo Vincent, 2005-05-14.

import socket

def send(data, port=50000, addr='239.192.1.100'):
"""send(data[, port[, addr]]) - multicasts a UDP datagram."""

Create the socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

Make the socket multicast-aware, and set TTL.

s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20) # Change TTL (=20) to suit

Send the data

s.sendto(data, (addr, port))

def recv(port=50000, addr="239.192.1.100", buf_size=1024):
"""recv([port[, addr[,buf_size]]]) - waits for a datagram and returns the data."""

Create the socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

Set some options to make it multicast-friendly

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except AttributeError:
pass # Some systems don't support SO_REUSEPORT
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 20)
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)

Bind to the port

s.bind(('', port))

Set some more multicast options

intf = socket.gethostbyname(socket.gethostname())
s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(intf) + socket.inet_aton('0.0.0.0'))
s.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr) + socket.inet_aton('0.0.0.0'))

Receive the data, then unregister multicast receive membership, then close the port

data, sender_addr = s.recvfrom(buf_size)
s.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, socket.inet_aton(addr) + socket.inet_aton('0.0.0.0'))
s.close()
return data

复制代码 代码如下:

!/usr/bin/env python

from socket import from time import sleep,time,ctime
HOST = '229.0.0.15'PORT = 9999BUFSIZ = 1024ADDR = (HOST, PORT)
udpCliSock = socket(AF_INET, SOCK_DGRAM)
data = 't'
200count = 0while(count<100 ): udpCliSock.sendto(data, ADDR) sleep(1) count = count+1
udpCliSock.close()

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8