Ejemplo n.º 1
0
   def __init__(self,SLFfileName,CLMfileName,SEQfileName='',splitCONLIM=False,DOMfileRoot=''):

      print '\n... Acquiring global files'
      # ~~> Acquire global CONLIM file
      print '    +> CONLIM file'
      self.clm = CONLIM(CLMfileName)
      self.isCONLIM = splitCONLIM

      # ~~> Acquire global SELAFIN file
      print '    +> SELAFIN file'
      self.slf = SELAFIN(SLFfileName)

      # ~~> Acquire global SELAFIN file
      if SEQfileName != '':
         print '    +> SEQUENCE file'
         self.NPARTS,self.NSPLIT,self.KSPLIT = self.getSplitFromSequence(np.array( getFileContent(SEQfileName), dtype='<i4' ))
      else:
         self.NPARTS,self.NSPLIT,self.KSPLIT = self.getSplitFromNodeValues('PROCESSORS')

      print '\n... Split by elements in ',self.NPARTS,' parts\n'

      # ~~> Clean inconsistencies in boundary segments
      self.IPOBO,self.NSPLIT,self.KSPLIT = self.setSplitForBoundaries(self.NSPLIT,self.clm.KFRGL,self.KSPLIT)

      self.PINTER,self.PNHALO,self.PNODDS = \
         self.setSplitForElements( self.IPOBO,self.NPARTS,self.NSPLIT,self.KSPLIT )
      self.slfn = self.copyCommonData()

      # ~~> Optional output file names
      self.isDOMAIN = DOMfileRoot
Ejemplo n.º 2
0
    def __init__(self,
                 SLFfileName,
                 CLMfileName,
                 SEQfileName='',
                 splitCONLIM=False,
                 DOMfileRoot=''):

        print '\n... Acquiring global files'
        # ~~> Acquire global CONLIM file
        print '    +> CONLIM file'
        self.clm = CONLIM(CLMfileName)
        self.isCONLIM = splitCONLIM

        # ~~> Acquire global SELAFIN file
        print '    +> SELAFIN file'
        self.slf = SELAFIN(SLFfileName)

        # ~~> Acquire global SELAFIN file
        if SEQfileName != '':
            print '    +> SEQUENCE file'
            self.NPARTS, self.NSPLIT, self.KSPLIT = self.getSplitFromSequence(
                np.array(getFileContent(SEQfileName), dtype='<i4'))
        else:
            self.NPARTS, self.NSPLIT, self.KSPLIT = self.getSplitFromNodeValues(
                'PROCESSORS')

        print '\n... Split by elements in ', self.NPARTS, ' parts\n'

        # ~~> Clean inconsistencies in boundary segments
        self.IPOBO, self.NSPLIT, self.KSPLIT = self.setSplitForBoundaries(
            self.NSPLIT, self.clm.KFRGL, self.KSPLIT)

        self.PINTER,self.PNHALO,self.PNODDS = \
           self.setSplitForElements( self.IPOBO,self.NPARTS,self.NSPLIT,self.KSPLIT )
        self.slfn = self.copyCommonData()

        # ~~> Optional output file names
        self.isDOMAIN = DOMfileRoot
Ejemplo n.º 3
0
# _____             ________________________________________________
# ____/ MAIN CALL  /_______________________________________________/
#

__author__ = "Sebastien E. Bourban"
__date__ = "$29-Feb-2012 08:51:29$"

if __name__ == "__main__":

    PWD = getcwd()
    partelName = path.join(PWD, 'PARTEL.PAR')
    if not path.exists(partelName):
        print '... could not find the PARTEL.PAR file in ', PWD
        sys.exit()
    files = getFileContent(partelName)
    fileSLF = path.join(PWD, files[0].strip())
    if not path.exists(fileSLF):
        print '... could not find the file ', fileSLF, ' in ', PWD
        sys.exit()
    fileCLM = path.join(PWD, files[1].strip())
    if not path.exists(fileCLM):
        print '... could not find the file ', fileCLM, ' in ', PWD
        sys.exit()
    fileSEQ = path.join(PWD, 'RESULT_SEQ_METIS')
    if not path.exists(fileSEQ): fileSEQ = ''
    splitCONLIM = False
    if len(files) > 5: splitCONLIM = (int(files[5].strip()) == 1)
    writeDOMAIN = ''
    if len(files) > 6:
        if int(files[6].strip()) == 1: writeDOMAIN = 'T2DBND'
Ejemplo n.º 4
0
# _____             ________________________________________________
# ____/ MAIN CALL  /_______________________________________________/
#

__author__="Sebastien E. Bourban"
__date__ ="$29-Feb-2012 08:51:29$"

if __name__ == "__main__":

   PWD = getcwd()
   partelName = path.join(PWD,'PARTEL.PAR')
   if not path.exists(partelName):
      print '... could not find the PARTEL.PAR file in ',PWD
      sys.exit(1)
   files = getFileContent(partelName)
   fileSLF = path.join(PWD,files[0].strip())
   if not path.exists(fileSLF):
      print '... could not find the file ',fileSLF,' in ',PWD
      sys.exit(1)
   fileCLM = path.join(PWD,files[1].strip())
   if not path.exists(fileCLM):
      print '... could not find the file ',fileCLM,' in ',PWD
      sys.exit(1)
   fileSEQ = path.join(PWD,'RESULT_SEQ_METIS')
   if not path.exists(fileSEQ): fileSEQ = ''
   splitCONLIM = False
   if len(files) > 5: splitCONLIM = ( int(files[5].strip()) == 1 )
   writeDOMAIN = ''
   if len(files) > 6:
      if int(files[6].strip()) == 1: writeDOMAIN = 'T2DBND'
Ejemplo n.º 5
0
	def run(self):
		inputs = [self.sock]
		outputs = []
		msgQueues = {}
		while self.runFlag:
			readable,writable,exceptional=select.select(inputs,outputs,inputs,0.1)
			for s in readable:
				if s is self.sock:
					conn,cli_addr = s.accept()
					conn.setblocking(0)
					print "connection from",cli_addr
					inputs.append(conn)
					msgQueues[conn]=Queue.Queue()
				else:#connection is created
					data = s.recv(1024)
					if data:
						#print "received ",data," from ", s.getpeername()
                                                #print data
						a,b,c,d = struct.unpack(DGRAM_FORMAT,data)
						a = a.strip("\x00")
						#注册新用户
						if a=='SIGN_IN':
                                                        user_no = login.register(b.strip("\x00"),c.strip("\x00"),d.strip("\x00"))
                                                        print u"随机生成一个OC号:",user_no
                                                        user_no = "%i" %user_no
                                                        msgQueues[s].put(user_no)
                                                        friends.addFriend(user_no,user_no)
                                                #登录验证
                                                elif a=='LOGIN':
                                                        uno = b.strip("\x00")
                                                        reply = login.loginCheck(uno,c.strip("\x00"))
                                                        msgQueues[s].put(reply)
                                                        if reply!="LOGIN FAIL":#登录成功
                                                                self.onlineUser.append(uno)
                                                                sdata = struct.pack("50s50s50s","UP",uno,"")
                                                                for kno in self.cmd_sock:
                                                                        if self.cmd_sock[kno] in msgQueues:
                                                                                msgQueues[self.cmd_sock[kno]].put(sdata)
                                                #客户端下线通知
                                                elif a =='DOWN':
                                                        uno = b.strip("\x00")
                                                        print u"%s下线通知" %uno
                                                        if uno in self.onlineUser:
                                                                self.onlineUser.remove(uno)
                                                        if uno in self.sessions:
                                                                for fno in self.sessions[uno]:
                                                                        usock = self.sessions[uno][fno]
                                                                        if usock:
                                                                                usock.close()
                                                                        self.sessions.pop(uno)
        
                                                        sdata = struct.pack("50s50s50s","DOWN",uno,"")
                                                        for kno in self.cmd_sock:
                                                                if self.cmd_sock[kno] in msgQueues:
                                                                        msgQueues[self.cmd_sock[kno]].put(sdata)
                                                #每个客户端一个cmd socket
                                                elif a=='CMD_SOCKET':
                                                        uno = b.strip('\x00')
                                                        self.cmd_sock[uno]=s
                                                #查找好友列表,返回user_no, nickname
                                                elif a=='GET_FRIENDS':
                                                        reply = friends.getFriends(b.strip("\x00"))
                                                        msgQueues[s].put(reply)
                                                #获取当前在线的所账号
                                                elif a=='GET_ONLINE':
                                                        reply = "OK"+self.getOnline()
                                                        msgQueues[s].put(reply)
                                                #查找好友
                                                elif a=='FIND_FRIEND':
                                                        reply = friends.findFriend(b.strip("\x00"))
                                                        msgQueues[s].put(reply)
                                                #添加好友,双向添加,默认不提示被动添加的一方
                                                elif a=='ADD_FRIEND':
                                                        uno = b.strip("\x00")
                                                        fno = c.strip("\x00")
                                                        
                                                        reply = friends.addFriend(fno,uno)
                                                        reply = friends.addFriend(uno,fno)
                                                        if reply == 'ADD_SUCCESS':
                                                                ret = friends.findFriend(fno)
                                                                fnick=ret.split('[')[1].split(']')[0]
                                                                state = "OFFLINE"
                                                                if fno in self.onlineUser:
                                                                        state = 'ONLINE'
                                                                reply = u"%s|%s|%s" %(fno,fnick,state)
                                                        msgQueues[s].put(reply)
                                                        

                                                #查找离线消息,返回send_user_no, msg
                                                elif a=='OFFLINE_MSG':
                                                        uno = b.strip('\x00')
                                                        sdata = message.getOfflineMsg(uno)
                                                        print u"离线消息:%s" %sdata
                                                        msgQueues[s].put(sdata)
                                                #建立会话、或接收会话
                                                elif a=='NEW_SESSION':
                                                        #or a=='ACC_SESSION':
                                                        user_no = b.strip("\x00")
                                                        friend_no = c.strip("\x00")
                                                        if user_no not in self.sessions.keys():
                                                                self.sessions[user_no]={}
                                                        self.sessions[user_no][friend_no] = s
                                                        print "new session between %s and %s" %(user_no,friend_no)
                                                                
                                                #转发消息
                                                elif a=='MESG':
                                                        user_no = b.strip("\x00")
                                                        friend_no = c.strip("\x00")
                                                        msg = d.strip('\x00')
                                                        print u"to %s: %s" %(friend_no,msg)
                                                        if friend_no not in self.onlineUser:
                                                                #写入离线消息文件,并提示
                                                                message.saveOfflineMsg(user_no,friend_no,msg)
                                                                msg = u"%s处于离线状态!" %friend_no
                                                                msgQueues[self.sessions[user_no][friend_no]].put(msg)
                                                                
                                                        else:
                                                                #如果friend_no和user_no还没有建立会话,那么先建立socket
                                                                if friend_no not in self.sessions.keys() or \
                                                                   user_no not in self.sessions[friend_no].keys():
                                                                        fsock = self.cmd_sock[friend_no]
                                                                        print "... cmd socket ",friend_no,fsock.getpeername()
                                                                        sdata = struct.pack("50s50s50s","NEW_SESSION",str(user_no),msg)
                                                                        msgQueues[fsock].put(sdata)
                                                                        print "MESG....deubg"
                                                                else:
                                                                        msgQueues[self.sessions[friend_no][user_no]].put(msg)
                                                                message.write2file(user_no,friend_no,msg)
                                                #上传文件
                                                elif a=='UPLOAD':
                                                        b = b.strip('\x00')
                                                        if len(b)==6:
                                                                sno = b.strip('\x00')
                                                                rno = c.strip('\x00')
                                                                fname = d.strip('\x00')
                                                                #print fname
                                                                msgQueues[self.sessions[sno][rno]].put(u"正在上传...")

                                                                msgQueues[s].put("RECV_NOTICE")
                                                                files.recordFileInfo(sno,rno,fname)
                                                        else:
                                                                dlen = string.atoi(b)
                                                                fname = c.strip('\x00')
                                                                cont = d
                                                                files.write2file(fname,cont[0:dlen])
                                                                msgQueues[s].put("RECV_OK")
                                                #上传完成
                                                elif a=='UPLOAD_FINISH':
                                                        sno = b.strip('\x00')
                                                        rno = c.strip('\x00')
                                                        fname = d.strip('\x00')
                                                        if rno in self.sessions and sno in self.sessions[rno]:
                                                                sdata = u"FILE\r\n%s|%s" %(sno,fname)
                                                                msgQueues[self.sessions[rno][sno]].put(sdata)
                                                        elif rno in self.onlineUser:
                                                                fsock = self.cmd_sock[rno]
                                                                print "... cmd socket ",rno,fsock.getpeername()
                                                                msg = u"%s正在向你传送文件:%s" %(sno,fname)
                                                                sdata = struct.pack("50s50s50s","NEW_SESSION",str(sno),str(msg))
                                                                msgQueues[fsock].put(sdata)
                                                                print "FILE....deubg"
                                                                
                                                                
                                                #可以下载的离线文件
                                                elif a=='DOWN_FILE_NAME':
                                                        fnames = files.getFileLists(b.strip("\x00"),c.strip("\x00"))
                                                        msgQueues[s].put(fnames)
                                                elif a=='DOWNLOAD':
                                                        fname = b.strip('\x00')
                                                        recvd_bytes = string.atoi(d.strip('\x00'))
                                                        if c.strip('\x00')=="RECV_OK":
                                                                rdata = files.getFileContent(fname,recvd_bytes,1024)
                                                                if len(rdata)<1:
                                                                        rdata = 'FILE_END\r\n'
                                                                msgQueues[s].put(rdata)
						if s not in outputs:
							outputs.append(s)
					else:
						print u"关闭socket: ", s.getpeername()
						if s in outputs:
							outputs.remove(s)
						for k1 in self.sessions.keys():
                                                        for k2 in self.sessions[k1].keys():
                                                                if self.sessions[k1][k2]==s:
                                                                        self.sessions[k1].pop(k2)
                                                                        break
						inputs.remove(s)
						s.close()
						del msgQueues[s]
			for s in writable:
                                if s not in msgQueues:
                                        continue
				try:
                                        nextMsg = msgQueues[s].get_nowait()
                                        #print u"sending %s to %s" %(nextMsg,s.getpeername())
                                        s.send(nextMsg)
				except Queue.Empty:
                                        pass
                                        
			for s in exceptional:
				print "exceptional condition on ",s.getpeername()
				inputs.remove(s)
				if s in outputs:
					outputs.remove(s)
				s.close()
				del msgQueues[s]
Ejemplo n.º 6
0
    def run(self):
        self.sock = self.newSocket()
        inputs = [self.sock]
        outputs = []
        msgQueues = {}
        while self.runFlag:
            readable, writable, exceptional = \
                    select.select(inputs, outputs, inputs, 0.1)

            for s in readable:
                if s is self.sock:
                    conn, cli_addr = s.accept()
                    conn.setblocking(0)
                    logger.info('connection from {}'.format(cli_addr))
                    inputs.append(conn)
                    msgQueues[conn] = Queue.Queue()
                else:  # connection is created
                    data = s.recv(1024)
                    if data:
                        raw_fields = struct.unpack(DGRAM_FORMAT, data)
                        fields = [e.strip('\x00') for e in raw_fields]
                        a, b, c, d = fields
                        logger.debug('recv {} from {}'.format('#'.join(fields),
                                     s.getpeername()))

                        # 注册新用户
                        if a == 'SIGN_IN':
                            uid = login.register(b, c, d)
                            logger.info(u'随机生成一个OC号: {}'.format(uid))
                            msgQueues[s].put(uid)
                            friends.addFriend(uid, uid)

                        # 登录验证
                        elif a == 'LOGIN':
                            uid, pwd = b, c
                            reply = login.loginCheck(uid, pwd)
                            msgQueues[s].put(reply)
                            if reply != 'LOGIN FAIL':   # 登录成功
                                self.onlineUser.append(uid)
                                msg = struct.pack(CMD_FORMAT, 'UP', uid, '')
                                for kno in self.cmd_sock:
                                    if self.cmd_sock[kno] in msgQueues:
                                        msgQueues[self.cmd_sock[kno]].put(msg)

                        # 客户端下线通知
                        elif a == 'DOWN':
                            uid = b
                            logger.info(u'{} 下线通知'.format(uid))
                            if uid in self.onlineUser:
                                self.onlineUser.remove(uid)
                            if uid in self.sessions:
                                for fid in self.sessions[uid]:
                                    usock = self.sessions[uid][fid]
                                    if usock:
                                        usock.close()
                                self.sessions.pop(uid)

                            sdata = struct.pack(CMD_FORMAT, 'DOWN', uid, '')
                            for kno in self.cmd_sock:
                                if self.cmd_sock[kno] in msgQueues:
                                    msgQueues[self.cmd_sock[kno]].put(sdata)

                        # 每个客户端一个cmd socket
                        elif a == 'CMD_SOCKET':
                            uid = b
                            self.cmd_sock[uid] = s

                        # 查找好友列表,返回uid, nickname
                        elif a == 'GET_FRIENDS':
                            reply = friends.getFriends(b)
                            msgQueues[s].put(reply)

                        # 获取当前在线的所账号
                        elif a == 'GET_ONLINE':
                            ou = '|'.join(self.onlineUser)
                            reply = 'OK|' + ou
                            msgQueues[s].put(reply)

                        # 查找好友
                        elif a == 'FIND_FRIEND':
                            reply = friends.findFriend(b)
                            msgQueues[s].put(reply)

                        # 添加好友,双向添加,默认不提示被动添加的一方
                        elif a == 'ADD_FRIEND':
                            uid, fid = b, c

                            reply = friends.addFriend(uid, fid)
                            if reply == 'ADD_SUCCESS':
                                reply = friends.addFriend(fid, uid)
                                ret = friends.findFriend(fid)
                                fnick = ret.split('[')[1].split(']')[0]
                                state = 'OFFLINE'
                                if fid in self.onlineUser:
                                    state = 'ONLINE'

                                reply = u'{}|{}|{}'.format(fid, fnick, state)
                                msgQueues[s].put(reply)
                            else:
                                msgQueues[s].put(reply)

                        # 查找离线消息,返回send_uid, msg
                        elif a == 'OFFLINE_MSG':
                            uid = b
                            sdata = message.getOfflineMsg(uid)
                            logger.info(u'离线消息:{}'.format(sdata))
                            msgQueues[s].put(sdata)

                        # 建立会话、或接收会话
                        elif a == 'NEW_SESSION':
                            uid, fid = b, c
                            if uid not in self.sessions.keys():
                                self.sessions[uid] = {}
                            self.sessions[uid][fid] = s
                            logger.info('new session between {} and {}'.format(uid, fid))

                        # 转发消息
                        elif a == 'MESG':
                            uid, fid, msg = b, c, d
                            logger.info(u'to {}: {}'.format(fid, msg))
                            if fid not in self.onlineUser:
                                # 写入离线消息文件,并提示
                                message.saveOfflineMsg(uid, fid, msg)
                                msg = u'{}处于离线状态!'.format(fid)
                                msgQueues[self.sessions[uid][fid]].put(msg)
                            else:
                                # 如果fid和uid还没有建立会话,那么先建立socket
                                if fid not in self.sessions.keys() or \
                                        uid not in self.sessions[fid].keys():
                                    fsock = self.cmd_sock[fid]
                                    logger.info('... cmd socket {} {}'.format(
                                                fid, fsock.getpeername()))
                                    sdata = struct.pack(CMD_FORMAT,
                                                        'NEW_SESSION',
                                                        str(uid),
                                                        msg)
                                    msgQueues[fsock].put(sdata)
                                    logger.debug('MESG....deubg')
                                else:
                                    msgQueues[self.sessions[fid][uid]].put(msg)

                                message.write2file(uid, fid, msg)

                        # 上传文件
                        elif a == 'UPLOAD':
                            if len(b) == 6 and len(c) == 6:  # todo: 区分upload cmd和data
                                send_uid, recv_uid, filename = b, c, d
                                msgQueues[self.sessions[send_uid][recv_uid]].\
                                    put(u'正在上传...')

                                msgQueues[s].put('RECV_NOTICE')
                                files.recordFileInfo(send_uid, recv_uid, filename)
                            else:
                                datalen = string.atoi(b)
                                filename, content = c, raw_fields[-1]
                                files.write2file(filename, content[0:datalen])
                                msgQueues[s].put('RECV_OK')

                        # 上传完成
                        elif a == 'UPLOAD_FINISH':
                            send_uid, recv_uid, filename = b, c, d

                            if recv_uid in self.sessions and \
                                    send_uid in self.sessions[recv_uid]:
                                sdata = u'FILE\r\n{}|{}'.format(send_uid, filename)
                                msgQueues[self.sessions[recv_uid][send_uid]].put(sdata)
                            elif recv_uid in self.onlineUser:
                                fsock = self.cmd_sock[recv_uid]
                                logger.info('... cmd socket {} {}'.format(
                                            recv_uid, fsock.getpeername()))
                                msg = u'{}正在向你传送文件:{}'.format(send_uid, filename)
                                sdata = struct.pack(CMD_FORMAT, 'NEW_SESSION',
                                                    send_uid, str(msg))
                                msgQueues[fsock].put(sdata)
                                logger.debug('FILE....deubg')

                        # 可以下载的离线文件
                        elif a == 'DOWN_FILE_NAME':
                            fs = files.getFileLists(b, c)
                            msgQueues[s].put(fs)
                        elif a == 'DOWNLOAD':
                            filename, status, size = b, c, d
                            recvd_bytes = string.atoi(size)
                            if status == 'RECV_OK':
                                rdata = files.getFileContent(filename, recvd_bytes, 1024)
                                if len(rdata) < 1:
                                    rdata = 'FILE_END\r\n'
                                msgQueues[s].put(rdata)

                        if s not in outputs:
                            outputs.append(s)
                    else:   # data is None
                        logger.info(u'关闭socket: {}'.format(s.getpeername()))
                        if s in outputs:
                            outputs.remove(s)
                        for k1 in self.sessions.keys():
                            for k2 in self.sessions[k1].keys():
                                if self.sessions[k1][k2] == s:
                                    self.sessions[k1].pop(k2)
                                    break
                        inputs.remove(s)
                        s.close()
                        del msgQueues[s]

            for s in writable:
                if s not in msgQueues:
                    continue
                try:
                    nextMsg = msgQueues[s].get_nowait()
                    s.send(nextMsg)
                except Queue.Empty:
                    pass

            for s in exceptional:
                logger.error('exceptional condition on {}'.format(s.getpeername()))
                inputs.remove(s)
                if s in outputs:
                    outputs.remove(s)
                s.close()
                del msgQueues[s]
Ejemplo n.º 7
0
    def run(self):
        self.sock = self.newSocket()
        inputs = [self.sock]
        outputs = []
        msgQueues = {}
        while self.runFlag:
            readable, writable, exceptional = \
                    select.select(inputs, outputs, inputs, 0.1)

            for s in readable:
                if s is self.sock:
                    conn, cli_addr = s.accept()
                    conn.setblocking(0)
                    logger.info('connection from {}'.format(cli_addr))
                    inputs.append(conn)
                    msgQueues[conn] = Queue.Queue()
                else:  # connection is created
                    data = s.recv(1024)
                    if data:
                        raw_fields = struct.unpack(DGRAM_FORMAT, data)
                        fields = [e.strip('\x00') for e in raw_fields]
                        a, b, c, d = fields
                        logger.debug('recv {} from {}'.format(
                            '#'.join(fields), s.getpeername()))

                        # 注册新用户
                        if a == 'SIGN_IN':
                            uid = login.register(b, c, d)
                            logger.info(u'随机生成一个OC号: {}'.format(uid))
                            msgQueues[s].put(uid)
                            friends.addFriend(uid, uid)

                        # 登录验证
                        elif a == 'LOGIN':
                            uid, pwd = b, c
                            reply = login.loginCheck(uid, pwd)
                            msgQueues[s].put(reply)
                            if reply != 'LOGIN FAIL':  # 登录成功
                                self.onlineUser.append(uid)
                                msg = struct.pack(CMD_FORMAT, 'UP', uid, '')
                                for kno in self.cmd_sock:
                                    if self.cmd_sock[kno] in msgQueues:
                                        msgQueues[self.cmd_sock[kno]].put(msg)

                        # 客户端下线通知
                        elif a == 'DOWN':
                            uid = b
                            logger.info(u'{} 下线通知'.format(uid))
                            if uid in self.onlineUser:
                                self.onlineUser.remove(uid)
                            if uid in self.sessions:
                                for fid in self.sessions[uid]:
                                    usock = self.sessions[uid][fid]
                                    if usock:
                                        usock.close()
                                self.sessions.pop(uid)

                            sdata = struct.pack(CMD_FORMAT, 'DOWN', uid, '')
                            for kno in self.cmd_sock:
                                if self.cmd_sock[kno] in msgQueues:
                                    msgQueues[self.cmd_sock[kno]].put(sdata)

                        # 每个客户端一个cmd socket
                        elif a == 'CMD_SOCKET':
                            uid = b
                            self.cmd_sock[uid] = s

                        # 查找好友列表,返回uid, nickname
                        elif a == 'GET_FRIENDS':
                            reply = friends.getFriends(b)
                            msgQueues[s].put(reply)

                        # 获取当前在线的所账号
                        elif a == 'GET_ONLINE':
                            ou = '|'.join(self.onlineUser)
                            reply = 'OK|' + ou
                            msgQueues[s].put(reply)

                        # 查找好友
                        elif a == 'FIND_FRIEND':
                            reply = friends.findFriend(b)
                            msgQueues[s].put(reply)

                        # 添加好友,双向添加,默认不提示被动添加的一方
                        elif a == 'ADD_FRIEND':
                            uid, fid = b, c

                            reply = friends.addFriend(uid, fid)
                            if reply == 'ADD_SUCCESS':
                                reply = friends.addFriend(fid, uid)
                                ret = friends.findFriend(fid)
                                fnick = ret.split('[')[1].split(']')[0]
                                state = 'OFFLINE'
                                if fid in self.onlineUser:
                                    state = 'ONLINE'

                                reply = u'{}|{}|{}'.format(fid, fnick, state)
                                msgQueues[s].put(reply)
                            else:
                                msgQueues[s].put(reply)

                        # 查找离线消息,返回send_uid, msg
                        elif a == 'OFFLINE_MSG':
                            uid = b
                            sdata = message.getOfflineMsg(uid)
                            logger.info(u'离线消息:{}'.format(sdata))
                            msgQueues[s].put(sdata)

                        # 建立会话、或接收会话
                        elif a == 'NEW_SESSION':
                            uid, fid = b, c
                            if uid not in self.sessions.keys():
                                self.sessions[uid] = {}
                            self.sessions[uid][fid] = s
                            logger.info('new session between {} and {}'.format(
                                uid, fid))

                        # 转发消息
                        elif a == 'MESG':
                            uid, fid, msg = b, c, d
                            logger.info(u'to {}: {}'.format(fid, msg))
                            if fid not in self.onlineUser:
                                # 写入离线消息文件,并提示
                                message.saveOfflineMsg(uid, fid, msg)
                                msg = u'{}处于离线状态!'.format(fid)
                                msgQueues[self.sessions[uid][fid]].put(msg)
                            else:
                                # 如果fid和uid还没有建立会话,那么先建立socket
                                if fid not in self.sessions.keys() or \
                                        uid not in self.sessions[fid].keys():
                                    fsock = self.cmd_sock[fid]
                                    logger.info('... cmd socket {} {}'.format(
                                        fid, fsock.getpeername()))
                                    sdata = struct.pack(
                                        CMD_FORMAT, 'NEW_SESSION', str(uid),
                                        msg)
                                    msgQueues[fsock].put(sdata)
                                    logger.debug('MESG....deubg')
                                else:
                                    msgQueues[self.sessions[fid][uid]].put(msg)

                                message.write2file(uid, fid, msg)

                        # 上传文件
                        elif a == 'UPLOAD':
                            if len(b) == 6 and len(
                                    c) == 6:  # todo: 区分upload cmd和data
                                send_uid, recv_uid, filename = b, c, d
                                msgQueues[self.sessions[send_uid][recv_uid]].\
                                    put(u'正在上传...')

                                msgQueues[s].put('RECV_NOTICE')
                                files.recordFileInfo(send_uid, recv_uid,
                                                     filename)
                            else:
                                datalen = string.atoi(b)
                                filename, content = c, raw_fields[-1]
                                files.write2file(filename, content[0:datalen])
                                msgQueues[s].put('RECV_OK')

                        # 上传完成
                        elif a == 'UPLOAD_FINISH':
                            send_uid, recv_uid, filename = b, c, d

                            if recv_uid in self.sessions and \
                                    send_uid in self.sessions[recv_uid]:
                                sdata = u'FILE\r\n{}|{}'.format(
                                    send_uid, filename)
                                msgQueues[self.sessions[recv_uid]
                                          [send_uid]].put(sdata)
                            elif recv_uid in self.onlineUser:
                                fsock = self.cmd_sock[recv_uid]
                                logger.info('... cmd socket {} {}'.format(
                                    recv_uid, fsock.getpeername()))
                                msg = u'{}正在向你传送文件:{}'.format(
                                    send_uid, filename)
                                sdata = struct.pack(CMD_FORMAT, 'NEW_SESSION',
                                                    send_uid, str(msg))
                                msgQueues[fsock].put(sdata)
                                logger.debug('FILE....deubg')

                        # 可以下载的离线文件
                        elif a == 'DOWN_FILE_NAME':
                            fs = files.getFileLists(b, c)
                            msgQueues[s].put(fs)
                        elif a == 'DOWNLOAD':
                            filename, status, size = b, c, d
                            recvd_bytes = string.atoi(size)
                            if status == 'RECV_OK':
                                rdata = files.getFileContent(
                                    filename, recvd_bytes, 1024)
                                if len(rdata) < 1:
                                    rdata = 'FILE_END\r\n'
                                msgQueues[s].put(rdata)

                        if s not in outputs:
                            outputs.append(s)
                    else:  # data is None
                        logger.info(u'关闭socket: {}'.format(s.getpeername()))
                        if s in outputs:
                            outputs.remove(s)
                        for k1 in self.sessions.keys():
                            for k2 in self.sessions[k1].keys():
                                if self.sessions[k1][k2] == s:
                                    self.sessions[k1].pop(k2)
                                    break
                        inputs.remove(s)
                        s.close()
                        del msgQueues[s]

            for s in writable:
                if s not in msgQueues:
                    continue
                try:
                    nextMsg = msgQueues[s].get_nowait()
                    s.send(nextMsg)
                except Queue.Empty:
                    pass

            for s in exceptional:
                logger.error('exceptional condition on {}'.format(
                    s.getpeername()))
                inputs.remove(s)
                if s in outputs:
                    outputs.remove(s)
                s.close()
                del msgQueues[s]