Changeset 1584


Ignore:
Timestamp:
01/20/10 20:33:32 (2 years ago)
Author:
tolteque
Message:

o Lotatc:

  • Modify radarServer to send and receive frame in the new Fashion.

--- OF COURSE NOT TESTED --- :)

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/lotatc_server/lotatc_radarServer.py

    r1276 r1584  
    2525from configuration_object     import ConfigurationObject 
    2626from lotatc_radarList         import * 
     27from cnxObj                   import *   
    2728 
    2829# List of commands 
     
    8687    self.logger.debug('__init__') 
    8788     
     89    # Create cnxObj used to communicate with RadarClient 
     90    self.cnxObj = CnxObj( request) 
     91     
    8892    # This is the PSEUDO of the troller 
    8993    self.controllerId = None 
     
    9599    # This the dictionary used for the objects sent to this troller 
    96100    self.objects={} 
    97      
    98101     
    99102    # There is no protection, but there is not a lot of risk ... 
     
    159162  # @param self  instance id 
    160163  def handle(self): 
    161  
    162     # 'incompleteMessage' is the start of a message which has been truncated during transmission ... 
    163     # It has to be prepend to the first message of the next buffer. 
    164     incompleteMessage="" 
    165  
    166164    while(True): 
    167       # Get one segment 
    168165      try: 
    169         buffer = self.request.recv(1024) 
    170         #- If client close the connection, buffer is void... 
    171         if not buffer: 
    172             #- Buffer void, return 
    173             return 
     166        frames = self.cnxObj.receiveFrame() 
     167        # Test if client has close the connection 
     168        if len( frames[0]): 
     169          return 
    174170      except: 
    175           return 
    176  
    177       # Detecte if the last message of the buffer is complete or not 
    178       if buffer.endswith( os.linesep): 
    179         lastMessageIsComplete = True 
    180       else: 
    181         lastMessageIsComplete = False 
     171        return 
    182172 
    183173      # Test for EndOfMission notified by LuaServer 
     
    197187      self.radarServer.coalitionLocks[cst_coalitionLut[0]].release() 
    198188 
    199       # split buffer in messages 
    200       msgList = buffer.split(os.linesep) 
    201        
    202       # If there is an incompleteMessage, pre-pend this incompleteMessage 
    203       # with the first message of the buffer. 
    204       if incompleteMessage !="": 
    205         msgList[0] = incompleteMessage + msgList[0] 
    206         incompleteMessage ="" 
    207        
    208       # Process each message 
    209       nbrMessages = len(msgList) 
    210       for index in range(nbrMessages): 
    211         if lastMessageIsComplete or (index != nbrMessages-1): 
    212           msg = msgList[index] 
    213           if len(msg) and msg != os.linesep: 
    214             data = msg.strip() 
    215             request = data.split("|", 1)[0] 
    216  
    217             if request == DATA_REQ: 
    218               self.dataRequest() 
    219  
    220             elif request == BROADCAST_REQ: 
    221               # items[1] => sendTo 
    222               # items[2] => incomming message 
    223               items = data.split("|", 2) 
    224               message = MSG + "|" + items[1] + "|" + self.controllerId + "|" + items[2] + os.linesep 
    225               self.server.broadcastMessage(message, self.controllerCoalition, items[1], self.controllerId) 
    226  
    227             elif request == TAG_SET: 
    228               self.tagObject(data) 
    229                  
    230             elif request == GRAPH_ADD: 
    231               self.graphAdd(data) 
    232                  
    233             elif request == GRAPH_DEL: 
    234               self.graphDelete(data) 
    235  
    236             elif request == GRAPH_MOD: 
    237               self.graphModify(data) 
    238  
    239             elif request == GRAPH_MSG_ID_REQ: 
    240               self.graphGetMsgId(data) 
    241  
    242             elif request == GRAPH_LOCK_REQ: 
    243               self.graphLock(data) 
     189 
     190      # Process each received frame 
     191      for frame in frames: 
     192        opCode = frame.split("|", 1)[0] 
     193 
     194        if opCode == DATA_REQ: 
     195          self.dataRequest() 
     196 
     197        elif opCode == BROADCAST_REQ: 
     198          # items[1] => sendTo 
     199          # items[2] => incomming message 
     200          items = frame.split("|", 2) 
     201          message = MSG + "|" + items[1] + "|" + self.controllerId + "|" + items[2] 
     202          self.server.broadcastMessage(message, self.controllerCoalition, items[1], self.controllerId) 
     203 
     204        elif opCode == TAG_SET: 
     205          self.tagObject(frame) 
     206             
     207        elif opCode == GRAPH_ADD: 
     208          self.graphAdd(frame) 
     209             
     210        elif opCode == GRAPH_DEL: 
     211          self.graphDelete(frame) 
     212 
     213        elif opCode == GRAPH_MOD: 
     214          self.graphModify(frame) 
     215 
     216        elif opCode == GRAPH_MSG_ID_REQ: 
     217          self.graphGetMsgId(frame) 
     218 
     219        elif opCode == GRAPH_LOCK_REQ: 
     220          self.graphLock(frame) 
     221           
     222        elif opCode == GRAPH_UNLOCK_REQ: 
     223          self.graphUnlock(frame) 
     224 
     225        elif opCode == LOGIN: 
     226          self.login(frame) 
     227 
     228        elif opCode == CONFIG_REQ: 
     229          self.configRequest(frame) 
     230 
     231        elif opCode == MISSION_REQ: 
     232          self.sendMissionData() 
     233 
     234        elif opCode == SEND_TO_ONE_PLAYER: 
     235          items = frame.split("|", 2) 
     236          playerId = items[1] 
     237          message  = items[2] 
     238          self.server.sendToPlayer( playerId, message) 
     239         
     240        elif opCode == SEND_TO_ALL_PLAYERS: 
     241          self.server.sendToPlayer( None, frame.split("|", 1)[1]) 
     242           
     243        else: 
     244          self.logger.debug("Unkwon command: %s" % opCode) 
    244245               
    245             elif request == GRAPH_UNLOCK_REQ: 
    246               self.graphUnlock(data) 
    247  
    248             elif request == LOGIN: 
    249               self.login(data) 
    250  
    251             elif request == CONFIG_REQ: 
    252               self.configRequest(data) 
    253  
    254             elif request == MISSION_REQ: 
    255               self.sendMissionData() 
    256  
    257             elif request == SEND_TO_ONE_PLAYER: 
    258               items = data.split("|", 2) 
    259               playerId = items[1] 
    260               message  = items[2] 
    261               self.server.sendToPlayer( playerId, message) 
    262              
    263             elif request == SEND_TO_ALL_PLAYERS: 
    264               self.server.sendToPlayer( None, data.split("|", 1)[1]) 
    265                
    266             else: 
    267               self.logger.debug("Unkwon command: %s" % request) 
    268                
    269             # End of: if request == DATA_REQ 
    270           # End of: if len(msg) and msg != LINE_SEP 
    271         # End of: if lastMessageIsComplete or (index != nbrMessages-1): 
    272         else:  
    273           incompleteMessage = msgList[index] 
    274          
    275246      # End of: for index in range(nbrMessages): 
    276247    # End of: while(True): 
     
    293264            # Yes -> remove lock and notify other client about Unlock 
    294265            self.graph[graphId]["LockBy"] = None 
    295             self.server.broadcastMessage(GRAPH_UNLOCK_REP + "|%s|%s|%s" % (0, graphId, "1" + os.linesep), self.controllerCoalition, "ALL") 
     266            self.server.broadcastMessage( GRAPH_UNLOCK_REP + "|%s|%s|%s" % (0, graphId, "1"), self.controllerCoalition, "ALL") 
    296267        self.lock.release() 
    297268 
     
    318289          debugMessage = "|--> Incorrect client version" 
    319290          self.logger.debug(debugMessage) 
    320           self.request.send(LOGIN_NACK + debugMessage + os.linesep) 
     291          self.cnxObj.sendFrame( LOGIN_NACK + debugMessage) 
    321292          return 
    322293        if password == controllerPwd and self.radarServer.controllerOk(self): 
     
    327298          self.graph = self.mainInfo["GRAPH"][coalition] 
    328299          self.logger.info("The troller '%s' is working for '%s' coalition"  % (self.controllerId, self.controllerCoalition)) 
    329           self.request.send(LOGIN_ACK + "|%s|%s" % (coalition, str( CST_LOTATC_NETWORK_VERSION ) + os.linesep) ) 
     300          self.cnxObj.sendFrame( LOGIN_ACK + "|%s|%s" % (coalition, str( CST_LOTATC_NETWORK_VERSION)) ) 
    330301 
    331302          # MissionStartTime is to be sent 
     
    348319              message += "|%s|%s" % (key,graph["Data"]) 
    349320 
    350             message += os.linesep 
    351             self.request.send(message) 
     321            self.cnxObj.sendFrame( message) 
    352322          # End of: if len(self.graph): 
    353323 
     
    358328      debugMessage = "|--> Incorrect logging password" 
    359329      self.logger.debug(debugMessage) 
    360       self.request.send(LOGIN_NACK + debugMessage + os.linesep) 
     330      self.cnxObj.sendFrame( LOGIN_NACK + debugMessage) 
    361331    else: 
    362332      debugMessage = "|--> Incorrect logging message length" 
    363333      self.logger.debug(debugMessage) 
    364       self.request.send(LOGIN_NACK + debugMessage + os.linesep) 
     334      self.cnxObj.sendFrame( LOGIN_NACK + debugMessage) 
    365335    # End of: if len(items) == 3: 
    366336 
     
    388358 
    389359    # Send response 
    390     self.request.send(configRep + os.linesep) 
     360    self.cnxObj.sendFrame( configRep) 
    391361 
    392362 
     
    400370    if self.globalServerConfig.Mission: 
    401371      for m in self.globalServerConfig.Mission: 
    402         self.request.send(MISSION_REP + "|" + m + os.linesep) 
     372        self.cnxObj.sendFrame( MISSION_REP + "|" + m) 
    403373      # End of: for m in self.globalServerConfig.Mission: 
    404374         
    405375      # For the moment it is a stub 
    406       self.request.send(MISSION_END + os.linesep) 
     376      self.cnxObj.sendFrame(MISSION_END) 
    407377       
    408378    else: 
    409379      message = "Mission has not been imported ..." 
    410380      self.logger.debug(message) 
    411       self.request.send("%s|%s" % (MISSION_NACK, message+os.linesep)) 
     381      self.cnxObj.sendFrame("%s|%s" % ( MISSION_NACK, message)) 
    412382    # End of: if self.globalServerConfig.Mission: 
    413383 
     
    431401        if (self.mainObjects): 
    432402          # Send MissionStartTime 
    433           message = MISSION_START_TIME + "|%s\n" % self.mainInfo["MissionStartTime"] 
    434           self.request.send(message) 
     403          message = MISSION_START_TIME + "|%s" % self.mainInfo["MissionStartTime"] 
     404          self.cnxObj.sendFrame( message) 
    435405          self.sendMissionStartTime = False 
    436406          print "Send MissionStartTime" 
     
    439409      self.lock.acquire() 
    440410      # Send DATA_REP with timestamp for the time slot 
    441       message = "%s|%s\n" % (DATA_START,  self.mainInfo["TimeStamp"][self.controllerCoalition]) 
     411      frame = self.cnxObj.buildFrame( "%s|%s" % (DATA_START,  self.mainInfo["TimeStamp"][self.controllerCoalition])) 
    442412      # Loop over detected objects 
    443413      for (key, thisObject) in self.mainObjects.iteritems(): 
     
    448418          self.objects[key] = thisObject.clone() 
    449419#           self.logger.info("Static info for id:%s %s %s" % (key, thisObject.unitName, thisObject.pilotName)) 
    450           message = message + (DATA_REP0 + "|%s|%s|%s|%s|%s" % 
    451                               (key, thisObject.type.encode('utf-8'), thisObject.unitClsId, thisObject.pilotName.encode('utf-8'), thisObject.coalition + os.linesep)) 
     420          frame += self.cnxObj.buildFrame( DATA_REP0 + "|%s|%s|%s|%s|%s" % 
     421                                           (key, thisObject.type.encode('utf-8'), thisObject.unitClsId, thisObject.pilotName.encode('utf-8'), thisObject.coalition)) 
    452422                                             
    453423          # ------------------------------------------------------------------------------------ 
    454424          # Send  variable part 
    455           message = message + (DATA_REP1 + "|%s|%s|%s|%s|%s" % 
    456                                           (key, thisObject.x, thisObject.y, thisObject.z, str(thisObject.bearing) + os.linesep)) 
     425          frame += self.cnxObj.buildFrame( DATA_REP1 + "|%s|%s|%s|%s|%s" % 
     426                                           (key, thisObject.x, thisObject.y, thisObject.z, str(thisObject.bearing))) 
    457427 
    458428          # As it is a new object, test for Tag to be sent. 
    459429          if self.tag.has_key(key): 
    460430            tag = self.tag[key] 
    461             message = message + TAG_SET + "|%s|%s" % (key, tag + os.linesep) 
     431            frame += self.cnxObj.buildFrame( TAG_SET + "|%s|%s" % (key, tag)) 
    462432#             self.logger.info("Send tag id:%s Tag:%s" % (key, tag)) 
    463433          # End of: if self.tag.has_key(key): 
     
    467437#           self.logger.debug("Update info for id:%s Name:%s" % (key, localObject.unitName)) 
    468438          # We have just to send the differences 
    469           message = message + (DATA_REP1 + "|%s" % key) 
     439          message = (DATA_REP1 + "|%s" % key) 
    470440          if localObject.x != thisObject.x: 
    471441            message = message + ("|%s" % thisObject.x) 
     
    492462            message = message + "|" 
    493463           
    494           message = message + os.linesep 
     464          frame += self.cnxObj.buildFrame( message) 
    495465        # End of: if not self.objects.has_key(key):   
    496466      # End of: for (key, thisObject) in self.mainObjects.iteritems(): 
    497467       
    498468      # Send "end of transmition" 
    499       message = message + (DATA_END + os.linesep) 
    500       self.request.send(message) 
     469      frame += self.cnxObj.buildFrame( DATA_END) 
     470      self.cnxObj.sendFrame( message, multiFrame=True) 
    501471 
    502472 
     
    504474      # Check if there are new mobile radars 
    505475      newRadarFound = False 
    506       message = CONFIG_REP1 
     476      frame = CONFIG_REP1 
    507477      for (key, thisObject) in  self.mainObjects.iteritems(): 
    508478        if cst_coalitionLut[int(thisObject.coalition)] == self.controllerCoalition: 
     
    512482              newRadarFound = True 
    513483              self.mobileRadarKeys.append(key) 
    514               message = message + "|%s|%s|%s" % (key, thisObject.unitName.encode('utf-8'), thisObject.pilotName.encode('utf-8')) 
     484              frame = frame + "|%s|%s|%s" % (key, thisObject.unitName.encode('utf-8'), thisObject.pilotName.encode('utf-8')) 
    515485            # End of: if thisObject.unitName in self.mobileRadarTypes: 
    516486          # End of: if not (key in self.mobileRadarKeys): 
     
    519489       
    520490      if newRadarFound: 
    521         message = message + os.linesep 
    522         self.request.send(message) 
     491        self.cnxObj.sendFrame( frame) 
    523492      # End of: if newRadarFound: 
    524493           
     
    531500          # Radar has been killed, send a message and tag it as "to remove" 
    532501          self.logger.info("Radar killed: id:%s" % key) 
    533           message = "%s|%s%s" %(RADAR_KILLED, key, os.linesep) 
    534           self.request.send(message) 
     502          frame = "%s|%s" %( RADAR_KILLED, key) 
     503          self.cnxObj.sendFrame( frame) 
    535504          keysToRemove.append(key) 
    536505        # End of: if not self.mainObjects.has_key(key): 
     
    557526      message = "Login or ConfigSet is missing ..." 
    558527      self.logger.debug(message) 
    559       self.request.send(DATA_REQ_NACK + "|--> %s" % message + os.linesep) 
     528      self.cnxObj.sendFrame( DATA_REQ_NACK + "|--> %s" % message) 
    560529    # End of: if self.controllerId : 
    561530 
     
    566535  # @param message    message to be sent 
    567536  def sendMessage(self, message): 
    568     self.request.send(message) 
     537    self.cnxObj.sendFrame( message) 
    569538 
    570539 
     
    585554    # Save tag, then it is accessible by every troller. 
    586555    self.tag[objectId] = tag 
    587     self.server.broadcastMessage(TAG_SET + "|%s|%s" % (objectId, tag + os.linesep), self.controllerCoalition, "ALL") 
     556    self.server.broadcastMessage( TAG_SET + "|%s|%s" % (objectId, tag ), self.controllerCoalition, "ALL") 
    588557 
    589558# ============================================================ 
     
    611580  def graphDelete(self,  data): 
    612581    self.logger.info("GraphDel request") 
    613     items     = data.split("|", 1) 
    614     graphId   = items[1] 
     582    items   = data.split("|", 1) 
     583    graphId = items[1] 
    615584 
    616585    self.server.graphDelete( self.controllerCoalition, self.graph, graphId, self.controllerId, True) 
     
    634603      if self.graph[graphId]["LockBy"] == self.controllerId: 
    635604        self.graph[graphId]["Data"] = graphData 
    636         self.server.broadcastMessage(GRAPH_MOD + "|%s|%s" % (graphId, graphData + os.linesep), self.controllerCoalition, "ALL") 
     605        self.server.broadcastMessage( GRAPH_MOD + "|%s|%s" % (graphId, graphData), self.controllerCoalition, "ALL") 
    637606      else: 
    638607        self.logger.error("Troller %s tries to modify graph %s, but lock is missing" % (self.controllerId, graphId) )     
     
    654623    self.lock.acquire() 
    655624    print "ASSIGN", msgId, self.controllerId 
    656     self.server.broadcastMessage(GRAPH_MSG_ID_REP + "|%s" % (str(msgId) + os.linesep), self.controllerCoalition, self.controllerId) 
     625    self.server.broadcastMessage( GRAPH_MSG_ID_REP + "|%s" % (str(msgId)), self.controllerCoalition, self.controllerId) 
    657626    msgId += 1 
    658627    self.lock.release() 
     
    675644      if self.graph[graphId]["LockBy"] == None: 
    676645        self.graph[graphId]["LockBy"] = self.controllerId 
    677         self.server.broadcastMessage(GRAPH_LOCK_REP + "|%s|%s|%s" % (msgId, graphId, "1" + os.linesep), self.controllerCoalition, "ALL") 
     646        self.server.broadcastMessage( GRAPH_LOCK_REP + "|%s|%s|%s" % (msgId, graphId, "1"), self.controllerCoalition, "ALL") 
    678647      else: 
    679         self.server.broadcastMessage(GRAPH_LOCK_REP + "|%s|%s|%s" % (msgId, graphId, "0" + os.linesep), self.controllerCoalition, self.controllerId) 
     648        self.server.broadcastMessage( GRAPH_LOCK_REP + "|%s|%s|%s" % (msgId, graphId, "0"), self.controllerCoalition, self.controllerId) 
    680649 
    681650    else: 
     
    701670      if self.graph[graphId]["LockBy"] == self.controllerId: 
    702671        self.graph[graphId]["LockBy"] = None 
    703         self.server.broadcastMessage(GRAPH_UNLOCK_REP + "|%s|%s|%s" % (msgId, graphId, "1" + os.linesep), self.controllerCoalition, "ALL") 
     672        self.server.broadcastMessage( GRAPH_UNLOCK_REP + "|%s|%s|%s" % (msgId, graphId, "1"), self.controllerCoalition, "ALL") 
    704673      else: 
    705         self.server.broadcastMessage(GRAPH_UNLOCK_REP + "|%s|%s|%s" % (msgId, graphId, "0" + os.linesep), self.controllerCoalition, self.controllerId) 
     674        self.server.broadcastMessage( GRAPH_UNLOCK_REP + "|%s|%s|%s" % (msgId, graphId, "0"), self.controllerCoalition, self.controllerId) 
    706675    else: 
    707676      self.logger.warning("There is no graph with this key %s" % graphId)    
     
    837806      nbrOfTroller += 1 
    838807         
    839     message = message + os.linesep 
    840     self.broadcastMessage(message,  coalition,  "ALL") 
     808    self.broadcastMessage( message,  coalition,  "ALL") 
    841809 
    842810    self.luaServer.setTrollerNumber(coalition, nbrOfTroller) 
     
    872840      nbrOfTroller += 1 
    873841         
    874     message = message + os.linesep 
    875     self.broadcastMessage(message,  coalition,  "ALL") 
    876      
    877     self.luaServer.setTrollerNumber(coalition, nbrOfTroller) 
     842    self.broadcastMessage( message,  coalition,  "ALL") 
     843     
     844    self.luaServer.setTrollerNumber( coalition, nbrOfTroller) 
    878845 
    879846 
     
    887854  # @param controllerId    destination 
    888855  def broadcastMessage(self, message, coalition, controllerId, senderId=None): 
    889     self.logger.debug("broadcastMessage: '%s' to [%s, %s]" % (message, coalition, controllerId)) 
     856    self.logger.debug("broadcastMessage: '%s' to [%s, %s]" % ( message, coalition, controllerId)) 
    890857 
    891858    # Is the message to be sent to all the trollers ? 
     
    893860      # Yes => loop over all the trollers of the coalition 
    894861      for requestHandle in self.requestHandleInfo[coalition]: 
    895         requestHandle.sendMessage(message) 
     862        requestHandle.sendMessage( message) 
    896863 
    897864    else: 
     
    899866      for requestHandle in self.requestHandleInfo[coalition]: 
    900867        if requestHandle.controllerId == controllerId: 
    901           requestHandle.sendMessage(message) 
     868          requestHandle.sendMessage( message) 
    902869        elif requestHandle.controllerId == senderId: 
    903           requestHandle.sendMessage(message) 
     870          requestHandle.sendMessage( message) 
    904871        
    905872 
     
    930897      if ( check == False )  or  ( graphs[graphId]["LockBy"] == controlerId ): 
    931898        del graphs[graphId] 
    932         self.broadcastMessage(GRAPH_DEL + "|%s" % (graphId + os.linesep), coalition, "ALL") 
     899        self.broadcastMessage( GRAPH_DEL + "|%s" % graphId, coalition, "ALL") 
    933900      else: 
    934901        self.logger.error("Troller %s tries to delete graph %s, but lock is missing" % (controlerId, graphId) ) 
     
    956923    graphId = str(graphId) 
    957924    graphs[graphId] = {}  
    958     graphs[graphId]["Data"]    = graphData 
     925    graphs[graphId]["Data"]   = graphData 
    959926    graphs[graphId]["LockBy"] = None 
    960927    self.coalitionLocks[coalition].release() 
    961928       
    962929    # Broadcast message    
    963     self.broadcastMessage(GRAPH_ADD + "|%s|%s" % (graphId, graphData + os.linesep), coalition, "ALL") 
     930    self.broadcastMessage( GRAPH_ADD + "|%s|%s" % (graphId, graphData), coalition, "ALL") 
    964931     
    965932# ============================================================ 
  • trunk/textNewCnx.py

    r1582 r1584  
     1# -*- coding: utf-8 -*- 
     2# vim: ts=4:sw=4 
     3#    This file is part of LOME. 
     4# 
     5#    LOME is free software: you can redistribute it and/or modify 
     6#    it under the terms of the GNU General Public License as published by 
     7#    the Free Software Foundation, either version 3 of the License, or 
     8#    (at your option) any later version. 
     9# 
     10#    LOME is distributed in the hope that it will be useful, 
     11#    but WITHOUT ANY WARRANTY; without even the implied warranty of 
     12#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
     13#    GNU General Public License for more details. 
     14# 
     15#    You should have received a copy of the GNU General Public License 
     16#    along with LOME.  If not, see <http://www.gnu.org/licenses/>. 
     17#  
     18 
    119import os 
    220import sys 
     
    1432 
    1533 
     34sys.path.append( os.path.join( sys.path[0], 'common')) 
     35from cnxObj          import * 
    1636 
    17 #============================================================================== 
    18 ## Object used to send and receive data upon a socket or a request. 
    19 class BaseCnxObj(): 
    20  
    21   # Declaration of the two bits reserved for the transmission information 
    22   ZIPPED_DATA = 0x80000000 
    23   MULTI_FRAME = 0x40000000 
    24  
    25 # ---------------------------------------------------------------------------- 
    26   # Constructor 
    27   # @param self              object instance 
    28   def __init__( self): 
    29     pass 
    30  
    31 # ---------------------------------------------------------------------------- 
    32   # Methode used to build a multiFrame. 
    33   # @param self              object instance 
    34   # @param datas             datas to be sent 
    35   def buildFrame( self, datas): 
    36     datasLength = len(datas) 
    37     frame = struct.pack('L', datasLength) 
    38     frame += datas 
    39     return frame 
    40  
    41 # ---------------------------------------------------------------------------- 
    42   # Methode used to display frames from a multiframe. 
    43   # @param self              object instance 
    44   # @param multiFrame        multi frame to display 
    45   def displayMultiFrame( self, multiFrame): 
    46     index = 0 
    47     while ( index < len( multiFrame)): 
    48       length = struct.unpack('L', multiFrame[index:index+4])[0] 
    49       index += 4 
    50       print multiFrame[index:index+length] 
    51       index += length  
    52  
    53        
    54 # ---------------------------------------------------------------------------- 
    55   # Methode used to send a frame 
    56   # @param self              object instance 
    57   # @param datas             datas to be sent 
    58   # @param forceZip          flag used to force the the transmission of zipped data 
    59   # @param multiFrame        flag used to indicate that the frame is a multiframe 
    60   def sendFrame( self,  datas, forceZip=False, multiFrame=False): 
    61     # Process zip mode 
    62     datasLength = len(datas) 
    63     if forceZip or ( datasLength > 100): 
    64       datas = datas.encode("zip") 
    65       datasLength = len(datas) + self.ZIPPED_DATA 
    66      
    67     # Process multiFrame mode 
    68     if multiFrame == True: 
    69       datasLength += self.MULTI_FRAME 
    70      
    71     # Build message 
    72     message = struct.pack('L', datasLength) 
    73     message += datas 
    74  
    75     # Send message 
    76     self.send( message) 
    77  
    78  
    79 # ---------------------------------------------------------------------------- 
    80   # Methode used to receive a frame. It returns the clear data. 
    81   # @param self              object instance 
    82   def receiveFrame( self): 
    83     zippedData = False 
    84     multiFrame = False 
    85     # Read bufferLength from socket 
    86     buffer = "" 
    87     while( len( buffer) != 4): 
    88       buffer += self.recv( 4 - len( buffer)) 
    89       if buffer == "": 
    90         break 
    91      
    92     # Check if socket has been closed 
    93     if buffer != "": 
    94       dataLength = struct.unpack('L', buffer[0:4])[0] 
    95        
    96       # Process dataLength for zipped data 
    97       if dataLength >= self.ZIPPED_DATA: 
    98         zippedData = True 
    99         dataLength -= self.ZIPPED_DATA 
    100       if dataLength >= self.MULTI_FRAME: 
    101         multiFrame = True 
    102         dataLength -= self.MULTI_FRAME 
    103          
    104       # Receive datas 
    105       buffer = "" 
    106       while ( len( buffer) != dataLength): 
    107         buffer += self.recv( dataLength - len( buffer)) 
    108        
    109       # Unzip zipped data 
    110       if zippedData: 
    111         buffer = buffer.decode("zip") 
    112          
    113       # Extract each frame of the multiFrame 
    114       if multiFrame == True: 
    115         bufferArray = [] 
    116         index = 0 
    117         while ( index < len( buffer)): 
    118           length = struct.unpack('L', buffer[index:index+4])[0] 
    119           index += 4 
    120           bufferArray.append( buffer[index:index+length]) 
    121           index += length  
    122         return bufferArray 
    123          
    124     # Return data 
    125     return [buffer] 
    126      
    127      
    128 #============================================================================== 
    129 ## Object used to send and receive data upon a socket or a request. 
    130 class QTCnxObj( BaseCnxObj, QTcpSocket): 
    131  
    132 # ---------------------------------------------------------------------------- 
    133   # Constructor 
    134   # @param self              object instance 
    135   def __init__( self): 
    136     BaseCnxObj.__init__( self) 
    137     QTcpSocket.__init__( self) 
    138      
    139 # ---------------------------------------------------------------------------- 
    140   # Methode used to send a message 
    141   # @param self              object instance 
    142   # @param datas             datas to be sent 
    143   def send( self, datas): 
    144     self.write( datas) 
    145  
    146 # ---------------------------------------------------------------------------- 
    147   # Methode used to receive a message. It returns the clear data and a flag 
    148   # indicating if the data were zipped or not 
    149   # @param self              object instance 
    150   def recv( self, size): 
    151     return self.read( size) 
    152  
    153  
    154 #============================================================================== 
    155 ## Object used to send and receive data upon a socket or a request. 
    156 class CnxObj( BaseCnxObj): 
    157  
    158 # ---------------------------------------------------------------------------- 
    159   # Constructor 
    160   # @param self              object instance 
    161   def __init__( self, cnxObject): 
    162     BaseCnxObj.__init__( self) 
    163     self.cnxObj = cnxObject 
    164      
    165 # ---------------------------------------------------------------------------- 
    166   # Methode used to send a message 
    167   # @param self              object instance 
    168   # @param datas             datas to be sent 
    169   def send( self, datas): 
    170     self.cnxObj.send( datas) 
    171  
    172 # ---------------------------------------------------------------------------- 
    173   # Methode used to receive a message. It returns the clear data and a flag 
    174   # indicating if the data were zipped or not 
    175   # @param self              object instance 
    176   def recv( self, size): 
    177     return self.cnxObj.recv( size) 
    17837 
    17938#============================================================================== 
     
    21776        return 
    21877       
    219       if len( frames) and len(frames[0]): 
     78      if len( frames[0]): 
    22079        for frame in frames: 
    22180          print "Frame received: %s" % frame 
     
    259118  for index in range(0,5): 
    260119    frame += cnxObj.buildFrame( "This is the frame: %02d in a multiframe" % index) 
    261 #  cnxObj.displayMultiFrame( frame) 
    262120  cnxObj.sendFrame( frame, multiFrame = True) 
    263121   
     
    293151  status = app.exec_() 
    294152 
    295      
    296153  # Create and connect socket 
    297   #sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) 
    298   #print "socket created" 
    299   #try: 
    300   #  sock.connect( ( 'localhost', 10312)) 
    301   #  print "socket connected" 
    302   #except socket.error, msg: 
    303   #  print msg 
    304   #  return 
    305   #cnxObj = CnxObj( sock) 
    306   #cnxObj.sendFrame( "This is a buffer tansmitted in the clear mode") 
    307   #cnxObj.sendFrame( "This is a buffer tansmitted in the zip mode" ,  forceZip=True)     
    308   #cnxObj.sendFrame( "This is a buffer tansmitted in the zip mode\n"*10)     
    309  
    310   #sleep(2) 
    311   #sock.shutdown(2) 
    312   #sleep(1) 
     154  sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) 
     155  print "socket created" 
     156  try: 
     157    sock.connect( ( 'localhost', 10312)) 
     158    print "socket connected" 
     159  except socket.error, msg: 
     160    print msg 
     161    return 
     162  cnxObj = CnxObj( sock) 
     163  cnxObj.sendFrame( "This is a buffer tansmitted in the clear mode") 
     164  cnxObj.sendFrame( "This is a buffer tansmitted in the zip mode" ,  forceZip=True)     
     165  cnxObj.sendFrame( "This is a buffer tansmitted in the zip mode\n"*10)     
     166   
     167  sleep(1) 
     168  sock.shutdown(2) 
    313169 
    314170# ================================================= 
Note: See TracChangeset for help on using the changeset viewer.