select监听udp消息

服务端

#!/usr/bin/python2.6
# -*- coding:utf-8 -*-

import json
import socket
import select

def socketserver():
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock1.bind(('',8090))            # 监听udp的8090端口
    sock1.setblocking(1)             # 设置为非阻塞模式
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock2.bind(('0.0.0.0', 8092))    # 监听udp的8092组播端口,组播组设置为 244.1.1.1
    status = sock2.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                             socket.inet_aton('224.1.1.1') + socket.inet_aton('server IP'))
    sock2.setblocking(False)         # 设置为非阻塞模式
    while True:
        rlist,wlist,elist = select.select([sock1, sock2,],[sock1, sock2,],[sock1, sock2,])   # 进行监听
        for sock in rlist:
            msg = ""
            client_msg_json,client_addr = sock.recvfrom(1024)
            client_msg = json.loads(client_msg_json)
            if sock1 == sock:
                msg += "[Unicast]    "
            elif sock2 == sock:
                msg += "[Multicast]  "
            else:
                msg += "[Other]      "
            msg += 'Client: %s,\t\tInfo: %s' % (client_addr[0]+':'+str(client_addr[1]), client_msg.get('info'))
            print msg

if __name__ == '__main__':
    socketserver()

 

 代码改进:

#!/usr/bin/python2.6
# -*- coding:utf-8 -*-

import json
import socket
import select

class Request():
    def __init__(self,sock,callback):
        """
        初始化
        :param sock: client's socket
        :param callback: callback function
        """
        self.sock = sock
        self.callback = callback
 
    def fileno(self):
        return self.sock.fileno()


def func1(msg):
    print "Unicast     %s" % msg

def func2(msg):
    print "Multicast   %s" % msg

def socketserver():
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock1.bind(('',8090))
    sock1.setblocking(False)
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock2.bind(('0.0.0.0', 8092))
    status = sock2.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                             socket.inet_aton('224.1.1.1') + socket.inet_aton('server IP'))
    sock2.setblocking(False)
    obj1 = Request(sock1,func1)
    obj2 = Request(sock2,func2)
    obj_list = [obj1, obj2,]
    while True:
        rlist,wlist,elist = select.select(obj_list, obj_list, obj_list)
        for obj in rlist:
            client_msg_json,client_addr = obj.sock.recvfrom(1024)
            client_msg = json.loads(client_msg_json)
            obj.callback(client_msg.get('info', ''))

if __name__ == '__main__':
    socketserver()

 

 

普通客户端

#!/usr/bin/python2.6
# -*- coding:utf-8 -*-

import json
import time
from socket import *

def send_udp():
    s = socket(AF_INET,SOCK_DGRAM)
    data={'info':'udp msg'}
    while True:
        s.sendto(json.dumps(data), ('server IP',8090))
        print 'Send %s' % data.get('info')
        time.sleep(5)
    s.close()

if __name__ == '__main__':
    send_udp()

 

组播客户端

#!/usr/bin/python2.6
# -*- coding:utf-8 -*-

import json
import time
import struct
import socket

class MultiCastSend(object):
    def __init__(self,senderport=8091,myport=8092,mygroup='224.1.1.1',myttl=5):
        self.senderport = senderport
        self.myport = myport
        self.mygroup = mygroup
        self.myttl = myttl
    def multicast_send(self,info_dict):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        s.bind(('client IP', self.senderport))
        # Set Time-to-live (optional)
        ttl_bin = struct.pack('@i', self.myttl)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
        status = s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                              socket.inet_aton(self.mygroup) + socket.inet_aton('client IP'))
        s.sendto(json.dumps(info_dict), (self.mygroup, self.myport))
        print 'Send %s by multicast.' % info_dict.get('info')


if __name__ == '__main__':
    mcSend = MultiCastSend()
    while True:
        mcSend.multicast_send({'info':'mc msg'})
        time.sleep(5)

  

posted @ 2018-01-18 20:37  lixin[at]hitwh  阅读(1346)  评论(0编辑  收藏  举报