欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-11 09:01:03
首先声明,这不是我写的,而是我找到的,但是别人写的相当好。 复制代码 代码如下: # udp multicast examples, hugo vincent, 2005-...
首先声明,这不是我写的,而是我找到的,但是别人写的相当好。
复制代码 代码如下:

# 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()