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()
因篇幅问题不能全部显示,请点此查看更多更全内容