comparison orpg/networking/mplay_messaging.py @ 152:6081bdc2b8d5 beta

Traipse Beta 'OpenRPG' {091125-00} Traipse is a distribution of OpenRPG that is designed to be easy to setup and go. Traipse also makes it easy for developers to work on code without fear of sacrifice. 'Ornery-Orc' continues the trend of 'Grumpy' and adds fixes to the code. 'Ornery-Orc's main goal is to offer more advanced features and enhance the productivity of the user. Update Summary (Beta) Added Bookmarks Fix to Remote Admin Commands Minor fix to text based Server Fix to Pretty Print, from Core Fix to Splitter Nodes not being created Fix to massive amounts of images loading, from Core Added 'boot' command to remote admin Added confirmation window for sent nodes Minor changes to allow for portability to an OpenSUSE linux OS Miniatures Layer pop up box allows users to turn off Mini labels, from FlexiRPG Zoom Mouse plugin added Images added to Plugin UI Switching to Element Tree Map efficiency, from FlexiRPG Added Status Bar to Update Manager default_manifest.xml renamed to default_upmana.xml Cleaner clode for saved repositories New TrueDebug Class in orpg_log (See documentation for usage) Mercurial's hgweb folder is ported to upmana Pretty important update that can help remove thousands of dead children from your gametree. Children, <forms />, <group_atts />, <horizontal />, <cols />, <rows />, <height />, etc... are all tags now. Check your gametree and look for dead children!! New Gametree Recursion method, mapping, and context sensitivity. !Infinite Loops return error instead of freezing the software! New Syntax added for custom PC sheets Tip of the Day added, from Core and community Fixed Whiteboard ID to prevent random line or text deleting. Modified ID's to prevent non updated clients from ruining the fix.
author sirebral
date Wed, 25 Nov 2009 06:16:35 -0600
parents dcf4fbe09b70
children dcae32e219f1
comparison
equal deleted inserted replaced
150:6c5f46a5924b 152:6081bdc2b8d5
46 def myescape(data): 46 def myescape(data):
47 return escape(data,{"\"":""}) 47 return escape(data,{"\"":""})
48 48
49 class messenger: 49 class messenger:
50 def __init__(self, *args, **kwargs): 50 def __init__(self, *args, **kwargs):
51 #self.xml = component.get("xml") used once, no need for the object.
52 self.dir_struct = component.get("dir_struct") #used? 51 self.dir_struct = component.get("dir_struct") #used?
53 self.validate = component.get("validate") #used?? 52 self.validate = component.get("validate") #used??
54 #self.settings = component.get("settings") ## used once, no need for the object.
55 if kwargs.has_key('isServer'): 53 if kwargs.has_key('isServer'):
56 self.isServer = kwargs['isServer'] 54 self.isServer = kwargs['isServer']
57 else: 55 else:
58 self.isServer = False 56 self.isServer = False
59 self.listen_event = Event() 57 self.listen_event = Event()
119 self.protocol_version = kwargs['protocol_version'] or pass 117 self.protocol_version = kwargs['protocol_version'] or pass
120 self.client_string = kwargs['client_string'] or pass 118 self.client_string = kwargs['client_string'] or pass
121 119
122 120
123 def build_message(self, *args, **kwargs): 121 def build_message(self, *args, **kwargs):
124 #print args
125 message = '<' + args[0] 122 message = '<' + args[0]
126 123
127 #Setup the attributes of the message 124 #Setup the attributes of the message
128 if len(kwargs) > 0: 125 if len(kwargs) > 0:
129 for attrib in kwargs.keys(): 126 for attrib in kwargs.keys():
132 #Add the actual message if there is one 129 #Add the actual message if there is one
133 if len(args) > 1: 130 if len(args) > 1:
134 #Close the first part 131 #Close the first part
135 message += '>' 132 message += '>'
136 message += escape(args[1]) 133 message += escape(args[1])
137
138 #Close the whole thing 134 #Close the whole thing
139 message += '</' + args[0] + '>' 135 message += '</' + args[0] + '>'
140 else: 136 else: message += ' />'
141 message += ' />'
142 return message 137 return message
143 138
144 def disconnect(self): 139 def disconnect(self):
145 self.set_status(2) 140 self.set_status(2)
146 logger.debug("client stub " + self.ip +" disconnecting...") 141 logger.debug("client stub " + self.ip +" disconnecting...")
287 def message_handler(self, arg): 282 def message_handler(self, arg):
288 xml_dom = None 283 xml_dom = None
289 logger.note("message handler thread running...", ORPG_NOTE) 284 logger.note("message handler thread running...", ORPG_NOTE)
290 while self.alive or self.status == 'connected': 285 while self.alive or self.status == 'connected':
291 data = None 286 data = None
292 try: 287 try: data = self.inbox.get(0)
293 data = self.inbox.get(0)
294 except Queue.Empty: 288 except Queue.Empty:
295 time.sleep(0.25) #sleep 1/4 second 289 time.sleep(0.25) #sleep 1/4 second
296 continue 290 continue
297 bytes = len(data) 291 bytes = len(data)
298 if bytes < 5: 292 if bytes < 5: continue
299 continue
300 try: 293 try:
301 thread.start_new_thread(self.parse_incoming_dom,(str(data),)) 294 thread.start_new_thread(self.parse_incoming_dom,(str(data),))
302 #data has been passed... unlink from the variable references 295 #data has been passed... unlink from the variable references
303 #so data in passed objects doesn't change (python passes by reference) 296 #so data in passed objects doesn't change (python passes by reference)
304 del data 297 del data
309 if xml_dom: xml_dom.unlink() 302 if xml_dom: xml_dom.unlink()
310 logger.note("message handler thread exiting...") 303 logger.note("message handler thread exiting...")
311 self.inbox_event.set() 304 self.inbox_event.set()
312 305
313 def parse_incoming_dom(self, data): 306 def parse_incoming_dom(self, data):
314 #print data
315 xml_dom = None 307 xml_dom = None
316 try: 308 try:
317 xml_dom = component.get("xml").parseXml(data) 309 xml_dom = component.get("xml").parseXml(data)
318 xml_dom = xml_dom._get_documentElement() 310 xml_dom = xml_dom._get_documentElement()
319 self.message_action(xml_dom, data) 311 self.message_action(xml_dom, data)
340 # Wait to be told it's okay to start running 332 # Wait to be told it's okay to start running
341 self.startedEvent.wait() 333 self.startedEvent.wait()
342 334
343 # Loop as long as we have a connection 335 # Loop as long as we have a connection
344 while( self.get_status() == 'connected' ): 336 while( self.get_status() == 'connected' ):
345 try: 337 try: readMsg = self.outbox.get( block=1 )
346 readMsg = self.outbox.get( block=1 )
347
348 except Exception, text: 338 except Exception, text:
349 logger.exception("Exception: messenger->sendThread(): " + str(text) 339 logger.exception("Exception: messenger->sendThread(): " + str(text)
350
351 # If we are here, it's because we have data to send, no doubt! 340 # If we are here, it's because we have data to send, no doubt!
352 if self.status == 'connected': 341 if self.status == 'connected':
353 try: 342 try:
354 # Send the entire message, properly formated/encoded 343 # Send the entire message, properly formated/encoded
355 sent = self.sendMsg( self.sock, readMsg ) 344 sent = self.sendMsg( self.sock, readMsg )
356 except: 345 except: logger.exception("Exception: messenger->sendThread():\n" + traceback.format_exc()
357 logger.exception("Exception: messenger->sendThread():\n" + traceback.format_exc()
358 else: 346 else:
359 # If we are not connected, purge the data queue 347 # If we are not connected, purge the data queue
360 logger.note("Data queued without a connection, purging data from queue...") 348 logger.note("Data queued without a connection, purging data from queue...")
361 self.sendThreadExitEvent.set() 349 self.sendThreadExitEvent.set()
362 logger.note( "sendThread has terminated...") 350 logger.note( "sendThread has terminated...")
372 lp = pack( 'i', socket.htonl( length ) ) 360 lp = pack( 'i', socket.htonl( length ) )
373 361
374 try: 362 try:
375 # Send the encoded length 363 # Send the encoded length
376 sentl = sock.send( lp ) 364 sentl = sock.send( lp )
377
378 # Now, send the message the the length was describing 365 # Now, send the message the the length was describing
379 sentm = sock.send( msg ) 366 sentm = sock.send( msg )
380 if self.isServer: 367 if self.isServer: logger.debug("('data_sent', " + str(sentl+sentm) + ")")
381 logger.debug("('data_sent', " + str(sentl+sentm) + ")")
382 return sentm 368 return sentm
383 except socket.error, e: 369 except socket.error, e:
384 logger.exception("Socket Error: messenger->sendMsg(): " + traceback.format_exc()) 370 logger.exception("Socket Error: messenger->sendMsg(): " + traceback.format_exc())
385 except: 371 except:
386 logger.exception("Exception: messenger->sendMsg(): " + traceback.format_exc()) 372 logger.exception("Exception: messenger->sendMsg(): " + traceback.format_exc())
393 while( self.get_status() == 'connected' ): 379 while( self.get_status() == 'connected' ):
394 readMsg = self.recvMsg( self.sock ) 380 readMsg = self.recvMsg( self.sock )
395 381
396 # Make sure we didn't get disconnected 382 # Make sure we didn't get disconnected
397 bytes = len( readMsg ) 383 bytes = len( readMsg )
398 if bytes == 0: 384 if bytes == 0: break
399 break
400
401 # Check the length of the message 385 # Check the length of the message
402 bytes = len( readMsg ) 386 bytes = len( readMsg )
403
404 # Make sure we are still connected 387 # Make sure we are still connected
405 if bytes == 0: 388 if bytes == 0: break
406 break
407 else: 389 else:
408 # Pass along the message so it can be processed 390 # Pass along the message so it can be processed
409 self.inbox.put( readMsg ) 391 self.inbox.put( readMsg )
410 self.update_idle_time() #update the last message time 392 self.update_idle_time() #update the last message time
411 if bytes == 0: 393 if bytes == 0:
454 lenData = self.recvData( sock, self.lensize ) 436 lenData = self.recvData( sock, self.lensize )
455 437
456 # Now, convert to a usable form 438 # Now, convert to a usable form
457 (length,) = unpack( 'i', lenData ) 439 (length,) = unpack( 'i', lenData )
458 length = socket.ntohl( length ) 440 length = socket.ntohl( length )
459
460 # Read exactly the remaining amount of data 441 # Read exactly the remaining amount of data
461 msgData = self.recvData( sock, length ) 442 msgData = self.recvData( sock, length )
462 443
463 if self.isServer: 444 if self.isServer: logger.debug("('data_recv', " + str(length+4) + ")")
464 logger.debug("('data_recv', " + str(length+4) + ")") 445 except: logger.exception("Exception: messenger->recvMsg():\n" + traceback.format_exc())
465 except:
466 logger.exception("Exception: messenger->recvMsg():\n" + traceback.format_exc())
467 return msgData 446 return msgData
468 447
469 if __name__ == "__main__": 448 if __name__ == "__main__":
470 test = messenger(None) 449 test = messenger(None)
471 print test.build_message('hello', "This is a test message", attrib1="hello world", attrib2="hello world2", attrib3="hello world3") 450 print test.build_message('hello', "This is a test message", attrib1="hello world", attrib2="hello world2", attrib3="hello world3")