python asyncore 使用

import asyncore
import socket
import json

class EchoHandler(asyncore.dispatcher_with_send):
    def __init__(self,sock):
        asyncore.dispatcher_with_send.__init__(self,sock)
        self.__sock = sock
        
    def handle_read(self):
        data = self.recv(8192)
        #onlineQueue['o'] = "aaa"
        if  data: 
            user_id,action,msg = core.parseProcotol(data)
            if action == 'connect':
                if user_id in onlineQueue:
                    #onlineQueue[user_id].close()
                    del onlineQueue[user_id]
                    print "++"
                    print onlineQueue
                    print "--"
                
                '''
                online msg
                ''' 
                onlineQueue.setdefault(user_id,self.__sock)
                print onlineQueue
                core.broadcast(onlineQueue,data,user_id)          
            else:
                core.broadcast(onlineQueue,data,user_id)
'''      
        if data:
            self.send(data)
'''
class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is None:
            pass
        else:
            sock, addr = pair
            print 'Incoming connection from %s' % repr(addr)
            handler = EchoHandler(sock)

class KkCore:
    def __init__(self):
        pass
    def parseProcotol(self,data):
        #data = '{"user_id":"fa0d1388-46ab-49d7-84cb-264753ccd23","action":"connect","msg":""}'
        
        map_data = json.loads(data)
        #map_data = {"user_id":23,"action":"222","msg":"ee"}
        return map_data['user_id'],map_data['action'],map_data['msg']
        
    def broadcast(self,q,msg,user_id=None):
        if msg:
            for k,v in q.items():
                if user_id != k : v.send(msg)

        
if  __name__ == '__main__':
    onlineQueue = {}
    core = KkCore()
    server = EchoServer('', 8080)
    asyncore.loop()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值