python3标准库中提供了socketserver库来提供快速的TCP和UDP服务的实现,在工作中接触到了组播的问题,为了方便的测试业务,通过继承UDPServer类,并override了server_bind方法,实现了一个可以快速搭建组播服务的类,通过创建一个MulticastServer实例就可以进行组播通信了
import socket
from socketserver import UDPServer, DatagramRequestHandler
MCASTADDR = '225.12.3.1'
PORT = 3232
INTERFACE = '192.168.10.11'
class MulticastHandler(DatagramRequestHandler):
def handle(self):
print('get a multicast message:',self.rfile.readline())
class MulticastServer(UDPServer):
"""
Multicast UDP server class
"""
allow_reuse_address = True
multicast_loop = True
def __init__(self, interface, server_address, RequestHandlerClass, ttl=1, bind_and_activate=True):
"""Constructor. May be extended, do not override."""
self.interface = interface
self.ttl = ttl
UDPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
def server_bind(self):
if self.allow_reuse_address:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#self.socket.bind((interface,server_address[1])) # for windows we need use this type
self.socket.bind(self.server_address)
if self.multicast_loop:
self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) # set the socket option: allow the packet recieved by localhost
self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, \
socket.inet_aton(self.server_address[0])+socket.inet_aton(self.interface)) # set the socket option: IP_ADD_MEMBERSHIP to join the group
if self.ttl != 1:
self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.ttl) # set the socket option: IP_MULTICAST_TTL
self.server_address = self.socket.getsockname()
def main():
multiserver=MulticastServer(INTERFACE, (MCASTADDR,PORT), MulticastHandler)
multiserver.serve_forever()
if __name__ == '__main__':
main()
发送端的代码可以参考:http://blog.csdn.net/ztb3214/article/details/19285363
注意:DatagramRequestHandler的在收到消息后会调用finish方法,finish方法会默认向客户端发送一个长度为0的udp报文,如果不想发送这个报文,需要重写finish方法
PS: windows下和linux下进行bind的时候bind的参数不太一致,linux下bind的是组播地址,windows下bind的本机的IP地址,为什么出现这样的不一致还没弄清楚,有了解的大神请不吝赐教