diff orpg/networking/mplay_messaging.py @ 71:449a8900f9ac ornery-dev

Code refining almost completed, for this round. Some included files are still in need of some clean up, but this is test worthy.
author sirebral
date Thu, 20 Aug 2009 03:00:39 -0500
parents c54768cffbd4
children d1aff41c031b
line wrap: on
line diff
--- a/orpg/networking/mplay_messaging.py	Tue Aug 18 20:48:36 2009 -0500
+++ b/orpg/networking/mplay_messaging.py	Thu Aug 20 03:00:39 2009 -0500
@@ -36,22 +36,22 @@
 from xml.sax.saxutils import escape
 from struct import pack, unpack, calcsize
 from string import *
-from orpg.orpg_version import *
+from orpg.orpg_version import VERSION, PROTOCOL_VERSION, CLIENT_STRING, SERVER_MIN_CLIENT_VERSION
 import os
 import time
 
-from orpg.orpgCore import *
+from orpg.tools.orpg_log import logger
+from orpg.orpgCore import component
 
 def myescape(data):
     return escape(data,{"\"":""})
 
 class messenger:
     def __init__(self, *args, **kwargs):
-        self.log = component.get("log")
-        self.xml = component.get("xml")
-        self.dir_struct = component.get("dir_struct")
-        self.validate = component.get("validate")
-        self.settings = component.get("settings")
+        #self.xml = component.get("xml") used once, no need for the object.
+        self.dir_struct = component.get("dir_struct") #used?
+        self.validate = component.get("validate") #used??
+        #self.settings = component.get("settings") ## used once, no need for the object.
         if kwargs.has_key('isServer'):
             self.isServer = kwargs['isServer']
         else:
@@ -64,7 +64,7 @@
         self.exitEvent = Event()
         self.sendThreadExitEvent = Event()
         self.recvThreadExitEvent = Event()
-        self.port = int(self.settings.get_setting("port"))
+        self.port = int(component.get("settings").get_setting("port")) ##used even?
         self.ip = socket.gethostbyname(socket.gethostname())
         self.lensize = calcsize('i')
         self.mplay_type = ('disconnected', 'connected', 'disconnecting', 'group change', 'group change failed')
@@ -137,12 +137,12 @@
 
     def disconnect(self):
         self.set_status(2)
-        self.log.log("client stub " + self.ip +" disconnecting...", ORPG_DEBUG)
-        self.log.log("closing sockets...", ORPG_DEBUG)
+        logger.debug("client stub " + self.ip +" disconnecting...")
+        logger.debug("closing sockets...")
         try:
             self.sock.shutdown( 2 )
         except:
-            self.log.log("Caught exception:\n" + traceback.format_exc(), ORPG_GENERAL)
+            logger.general("Caught exception:\n" + traceback.format_exc())
         self.set_status(0)
 
     def reset(self, sock):
@@ -161,10 +161,10 @@
         try:
             (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player
         except:
-            self.log.log("Exception:  messenger->update_self_from_player():\n" + traceback.format_exc(), ORPG_GENERAL)
+            logger.general("Exception:  messenger->update_self_from_player():\n" + traceback.format_exc())
 
     def toxml(self, act):
-        self.log.log("DEPRECIATED! messenger->toxml()", ORPG_CRITICAL)
+        logger.exception("DEPRECIATED! messenger->toxml()")
         xml_data = self.build_message('player',
                                 name=myescape(self.name),
                                 action=act,
@@ -290,7 +290,7 @@
     #Message Handaling
     def message_handler(self, arg):
         xml_dom = None
-        self.log.log("message handler thread running...", ORPG_NOTE)
+        logger.note("message handler thread running...", ORPG_NOTE)
         while self.alive or self.status == 'connected':
             data = None
             try:
@@ -308,24 +308,24 @@
                 del data
                 data = None
             except Exception, e:
-                self.log.log(traceback.format_exc(), ORPG_GENERAL)
+                logger.general(traceback.format_exc())
                 if xml_dom: xml_dom.unlink()
         if xml_dom: xml_dom.unlink()
-        self.log.log("message handler thread exiting...", ORPG_NOTE)
+        logger.note("message handler thread exiting...")
         self.inbox_event.set()
 
     def parse_incoming_dom(self, data):
         #print data
         xml_dom = None
         try:
-            xml_dom = self.xml.parseXml(data)
+            xml_dom = component.get("xml").parseXml(data)
             xml_dom = xml_dom._get_documentElement()
             self.message_action(xml_dom, data)
 
         except Exception, e:
-            self.log.log("Error in parse of inbound message. Ignoring message.", ORPG_GENERAL)
-            self.log.log("\tOffending data(" + str(len(data)) + "bytes)=" + data, ORPG_GENERAL)
-            self.log.log("Exception=" + traceback.format_exc(), ORPG_GENERAL)
+            logger.general("Error in parse of inbound message. Ignoring message.")
+            logger.general("\tOffending data(" + str(len(data)) + "bytes)=" + data)
+            logger.general("Exception=" + traceback.format_exc())
         if xml_dom: xml_dom.unlink()
 
     def message_action(self, xml_dom, data):
@@ -333,8 +333,8 @@
         if self.msg_handlers.has_key(tag_name):
             self.msg_handlers[tag_name](xml_dom, data)
         else:
-            self.log.log("Unknown Message Type", ORPG_GENERAL)
-            self.log.log(data, ORPG_GENERAL)
+            logger.general("Unknown Message Type")
+            logger.general(data)
         #Message Action thread expires and closes here.
         return
 
@@ -350,7 +350,7 @@
                 readMsg = self.outbox.get( block=1 )
 
             except Exception, text:
-                self.log.log("Exception:  messenger->sendThread():  " + str(text), ORPG_CRITICAL)
+                logger.exception("Exception:  messenger->sendThread():  " + str(text)
 
             # If we are here, it's because we have data to send, no doubt!
             if self.status == 'connected':
@@ -358,12 +358,12 @@
                     # Send the entire message, properly formated/encoded
                     sent = self.sendMsg( self.sock, readMsg )
                 except:
-                    self.log.log("Exception:  messenger->sendThread():\n" + traceback.format_exc(), ORPG_CRITICAL)
+                    logger.exception("Exception:  messenger->sendThread():\n" + traceback.format_exc()
             else:
                 # If we are not connected, purge the data queue
-                self.log.log("Data queued without a connection, purging data from queue...", ORPG_NOTE)
+                logger.note("Data queued without a connection, purging data from queue...")
         self.sendThreadExitEvent.set()
-        self.log.log( "sendThread has terminated...", ORPG_NOTE)
+        logger.note( "sendThread has terminated...")
 
     def sendMsg( self, sock, msg ):
         """Very simple function that will properly encode and send a message to te
@@ -382,12 +382,12 @@
             # Now, send the message the the length was describing
             sentm = sock.send( msg )
             if self.isServer:
-                self.log.log("('data_sent', " + str(sentl+sentm) + ")", ORPG_DEBUG)
+                logger.debug("('data_sent', " + str(sentl+sentm) + ")")
             return sentm
         except socket.error, e:
-            self.log.log("Socket Error: messenger->sendMsg(): " +  traceback.format_exc(), ORPG_CRITICAL)
+            logger.exception("Socket Error: messenger->sendMsg(): " +  traceback.format_exc())
         except:
-            self.log.log("Exception:  messenger->sendMsg(): " +  traceback.format_exc(), ORPG_CRITICAL)
+            logger.exception("Exception:  messenger->sendMsg(): " +  traceback.format_exc())
 
     def recvThread( self, arg ):
         "Receiving thread.  This thread reads from the socket and writes to the data queue."
@@ -413,11 +413,11 @@
                 self.inbox.put( readMsg )
                 self.update_idle_time() #update the last message time
         if bytes == 0:
-            self.log.log("Remote has disconnected!", ORPG_NOTE)
+            logger.note("Remote has disconnected!")
             self.set_status(2)
         self.outbox.put( "" )    # Make sure the other thread is woken up!
         self.sendThreadExitEvent.set()
-        self.log.log("messenger->recvThread() has terminated...", ORPG_NOTE)
+        logger.note("messenger->recvThread() has terminated...")
 
     def recvData( self, sock, readSize ):
         """Simple socket receive method.  This method will only return when the exact
@@ -439,7 +439,7 @@
                     offset += rs
                     data += frag
         except socket.error, e:
-            self.log.log("Socket Error: messenger->recvData(): " +  str(e), ORPG_CRITICAL)
+            logger.exception("Socket Error: messenger->recvData(): " +  str(e))
             data = ""
         return data
 
@@ -465,9 +465,9 @@
             msgData = self.recvData( sock, length )
 
             if self.isServer:
-                self.log.log("('data_recv', " + str(length+4) + ")", ORPG_DEBUG)
+                logger.debug("('data_recv', " + str(length+4) + ")")
         except:
-            self.log.log("Exception: messenger->recvMsg():\n" + traceback.format_exc(), ORPG_CRITICAL)
+            logger.exception("Exception: messenger->recvMsg():\n" + traceback.format_exc())
         return msgData
 
 if __name__ == "__main__":