ConnectionRepository.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. from pandac.PandaModules import *
  2. from direct.task import Task
  3. from direct.directnotify import DirectNotifyGlobal
  4. from direct.distributed.DoInterestManager import DoInterestManager
  5. from direct.distributed.DoCollectionManager import DoCollectionManager
  6. from direct.showbase import GarbageReport
  7. from PyDatagram import PyDatagram
  8. from PyDatagramIterator import PyDatagramIterator
  9. import types
  10. import imp
  11. import gc
  12. class ConnectionRepository(
  13. DoInterestManager, DoCollectionManager, CConnectionRepository):
  14. """
  15. This is a base class for things that know how to establish a
  16. connection (and exchange datagrams) with a gameserver. This
  17. includes ClientRepository and AIRepository.
  18. """
  19. notify = DirectNotifyGlobal.directNotify.newCategory("ConnectionRepository")
  20. taskPriority = -30
  21. taskChain = None
  22. CM_HTTP=0
  23. CM_NET=1
  24. CM_NATIVE=2
  25. gcNotify = directNotify.newCategory("GarbageCollect")
  26. GarbageCollectTaskName = "allowGarbageCollect"
  27. GarbageThresholdTaskName = "adjustGarbageCollectThreshold"
  28. def __init__(self, connectMethod, config, hasOwnerView = False,
  29. threadedNet = None):
  30. assert self.notify.debugCall()
  31. if threadedNet is None:
  32. # Default value.
  33. threadedNet = config.GetBool('threaded-net', False)
  34. # let the C connection repository know whether we're supporting
  35. # 'owner' views of distributed objects (i.e. 'receives ownrecv',
  36. # 'I own this object and have a separate view of it regardless of
  37. # where it currently is located')
  38. CConnectionRepository.__init__(self, hasOwnerView, threadedNet)
  39. self.setWantMessageBundling(config.GetBool('want-message-bundling', 1))
  40. # DoInterestManager.__init__ relies on CConnectionRepository being
  41. # initialized
  42. DoInterestManager.__init__(self)
  43. DoCollectionManager.__init__(self)
  44. self.setPythonRepository(self)
  45. # Create a unique ID number for each ConnectionRepository in
  46. # the world, helpful for sending messages specific to each one.
  47. self.uniqueId = hash(self)
  48. # Accept this hook so that we can respond to lost-connection
  49. # events in the main thread, instead of within the network
  50. # thread (if there is one).
  51. self.accept(self.uniqueName('lostConnection'), self.lostConnection)
  52. self.config = config
  53. if self.config.GetBool('verbose-repository'):
  54. self.setVerbose(1)
  55. # Set this to 'http' to establish a connection to the server
  56. # using the HTTPClient interface, which ultimately uses the
  57. # OpenSSL socket library (even though SSL is not involved).
  58. # This is not as robust a socket library as NET's, but the
  59. # HTTPClient interface does a good job of negotiating the
  60. # connection over an HTTP proxy if one is in use.
  61. #
  62. # Set it to 'net' to use Panda's net interface
  63. # (e.g. QueuedConnectionManager, etc.) to establish the
  64. # connection. This is a higher-level layer build on top of
  65. # the low-level "native net" library. There is no support for
  66. # proxies. This is a good, general choice.
  67. #
  68. # Set it to 'native' to use Panda's low-level native net
  69. # interface directly. This is much faster than either http or
  70. # net for high-bandwidth (e.g. server) applications, but it
  71. # doesn't support the simulated delay via the start_delay()
  72. # call.
  73. #
  74. # Set it to 'default' to use an appropriate interface
  75. # according to the type of ConnectionRepository we are
  76. # creating.
  77. userConnectMethod = self.config.GetString('connect-method', 'default')
  78. if userConnectMethod == 'http':
  79. connectMethod = self.CM_HTTP
  80. elif userConnectMethod == 'net':
  81. connectMethod = self.CM_NET
  82. elif userConnectMethod == 'native':
  83. connectMethod = self.CM_NATIVE
  84. self.connectMethod = connectMethod
  85. if self.connectMethod == self.CM_HTTP:
  86. self.notify.info("Using connect method 'http'")
  87. elif self.connectMethod == self.CM_NET:
  88. self.notify.info("Using connect method 'net'")
  89. elif self.connectMethod == self.CM_NATIVE:
  90. self.notify.info("Using connect method 'native'")
  91. self.connectHttp = None
  92. self.http = None
  93. # This DatagramIterator is constructed once, and then re-used
  94. # each time we read a datagram.
  95. self.private__di = PyDatagramIterator()
  96. self.recorder = None
  97. self.readerPollTaskObj = None
  98. # This is the string that is appended to symbols read from the
  99. # DC file. The AIRepository will redefine this to 'AI'.
  100. self.dcSuffix = ''
  101. self._serverAddress = ''
  102. if self.config.GetBool('gc-save-all', 1):
  103. # set gc to preserve every object involved in a cycle, even ones that
  104. # would normally be freed automatically during garbage collect
  105. # allows us to find and fix these cycles, reducing or eliminating the
  106. # need to run garbage collects
  107. # garbage collection CPU usage is O(n), n = number of Python objects
  108. gc.set_debug(gc.DEBUG_SAVEALL)
  109. if self.config.GetBool('want-garbage-collect-task', 1):
  110. # manual garbage-collect task
  111. taskMgr.add(self._garbageCollect, self.GarbageCollectTaskName, 200)
  112. # periodically increase gc threshold if there is no garbage
  113. taskMgr.doMethodLater(self.config.GetFloat('garbage-threshold-adjust-delay', 5 * 60.),
  114. self._adjustGcThreshold, self.GarbageThresholdTaskName)
  115. self._gcDefaultThreshold = gc.get_threshold()
  116. def _garbageCollect(self, task=None):
  117. # allow a collect
  118. # enable automatic garbage collection
  119. gc.enable()
  120. # creating an object with gc enabled causes garbage collection to trigger if appropriate
  121. gct = GCTrigger()
  122. # disable the automatic garbage collect during the rest of the frame
  123. gc.disable()
  124. return Task.cont
  125. def _adjustGcThreshold(self, task):
  126. # do an unconditional collect to make sure gc.garbage has a chance to be
  127. # populated before we start increasing the auto-collect threshold
  128. # don't distribute the leak check from the client to the AI, they both
  129. # do these garbage checks independently over time
  130. numGarbage = GarbageReport.checkForGarbageLeaks()
  131. if numGarbage == 0:
  132. self.gcNotify.debug('no garbage found, doubling gc threshold')
  133. a, b, c = gc.get_threshold()
  134. gc.set_threshold(min(a * 2, 1 << 30), b, c)
  135. task.delayTime = task.delayTime * 2
  136. retVal = Task.again
  137. else:
  138. self.gcNotify.warning('garbage found, reverting gc threshold')
  139. # the process is producing garbage, stick to the default collection threshold
  140. gc.set_threshold(*self._gcDefaultThreshold)
  141. retVal = Task.done
  142. return retVal
  143. def generateGlobalObject(self, doId, dcname, values=None):
  144. def applyFieldValues(distObj, dclass, values):
  145. for i in range(dclass.getNumInheritedFields()):
  146. field = dclass.getInheritedField(i)
  147. if field.asMolecularField() == None:
  148. value = values.get(field.getName(), None)
  149. if value is None and field.isRequired():
  150. # Gee, this could be better. What would really be
  151. # nicer is to get value from field.getDefaultValue
  152. # or similar, but that returns a binary string, not
  153. # a python tuple, like the following does. If you
  154. # want to change something better, please go ahead.
  155. packer = DCPacker()
  156. packer.beginPack(field)
  157. packer.packDefaultValue()
  158. packer.endPack()
  159. unpacker = DCPacker()
  160. unpacker.setUnpackData(packer.getString())
  161. unpacker.beginUnpack(field)
  162. value = unpacker.unpackObject()
  163. unpacker.endUnpack()
  164. if value is not None:
  165. function = getattr(distObj, field.getName())
  166. if function is not None:
  167. function(*value)
  168. else:
  169. self.notify.error("\n\n\nNot able to find %s.%s"%(
  170. distObj.__class__.__name__, field.getName()))
  171. # Look up the dclass
  172. dclass = self.dclassesByName.get(dcname+self.dcSuffix)
  173. if dclass is None:
  174. #print "\n\n\nNeed to define", dcname+self.dcSuffix
  175. self.notify.warning("Need to define %s" % (dcname+self.dcSuffix))
  176. dclass = self.dclassesByName.get(dcname+'AI')
  177. if dclass is None:
  178. dclass = self.dclassesByName.get(dcname)
  179. # Create a new distributed object, and put it in the dictionary
  180. #distObj = self.generateWithRequiredFields(dclass, doId, di)
  181. # Construct a new one
  182. classDef = dclass.getClassDef()
  183. if classDef == None:
  184. self.notify.error("Could not create an undefined %s object."%(
  185. dclass.getName()))
  186. distObj = classDef(self)
  187. distObj.dclass = dclass
  188. # Assign it an Id
  189. distObj.doId = doId
  190. # Put the new do in the dictionary
  191. self.doId2do[doId] = distObj
  192. # Update the required fields
  193. distObj.generateInit() # Only called when constructed
  194. distObj.generate()
  195. if values is not None:
  196. applyFieldValues(distObj, dclass, values)
  197. distObj.announceGenerate()
  198. distObj.parentId = 0
  199. distObj.zoneId = 0
  200. # updateRequiredFields calls announceGenerate
  201. return distObj
  202. def readDCFile(self, dcFileNames = None):
  203. """
  204. Reads in the dc files listed in dcFileNames, or if
  205. dcFileNames is None, reads in all of the dc files listed in
  206. the Config.prc file.
  207. """
  208. dcFile = self.getDcFile()
  209. dcFile.clear()
  210. self.dclassesByName = {}
  211. self.dclassesByNumber = {}
  212. self.hashVal = 0
  213. if isinstance(dcFileNames, types.StringTypes):
  214. # If we were given a single string, make it a list.
  215. dcFileNames = [dcFileNames]
  216. dcImports = {}
  217. if dcFileNames == None:
  218. readResult = dcFile.readAll()
  219. if not readResult:
  220. self.notify.error("Could not read dc file.")
  221. else:
  222. searchPath = getModelPath().getValue()
  223. for dcFileName in dcFileNames:
  224. pathname = Filename(dcFileName)
  225. vfs.resolveFilename(pathname, searchPath)
  226. readResult = dcFile.read(pathname)
  227. if not readResult:
  228. self.notify.error("Could not read dc file: %s" % (pathname))
  229. #if not dcFile.allObjectsValid():
  230. # names = []
  231. # for i in range(dcFile.getNumTypedefs()):
  232. # td = dcFile.getTypedef(i)
  233. # if td.isBogusTypedef():
  234. # names.append(td.getName())
  235. # nameList = ', '.join(names)
  236. # self.notify.error("Undefined types in DC file: " + nameList)
  237. self.hashVal = dcFile.getHash()
  238. # Now import all of the modules required by the DC file.
  239. for n in range(dcFile.getNumImportModules()):
  240. moduleName = dcFile.getImportModule(n)[:]
  241. # Maybe the module name is represented as "moduleName/AI".
  242. suffix = moduleName.split('/')
  243. moduleName = suffix[0]
  244. suffix=suffix[1:]
  245. if self.dcSuffix in suffix:
  246. moduleName += self.dcSuffix
  247. elif self.dcSuffix == 'UD' and 'AI' in suffix: #HACK:
  248. moduleName += 'AI'
  249. importSymbols = []
  250. for i in range(dcFile.getNumImportSymbols(n)):
  251. symbolName = dcFile.getImportSymbol(n, i)
  252. # Maybe the symbol name is represented as "symbolName/AI".
  253. suffix = symbolName.split('/')
  254. symbolName = suffix[0]
  255. suffix=suffix[1:]
  256. if self.dcSuffix in suffix:
  257. symbolName += self.dcSuffix
  258. elif self.dcSuffix == 'UD' and 'AI' in suffix: #HACK:
  259. symbolName += 'AI'
  260. importSymbols.append(symbolName)
  261. self.importModule(dcImports, moduleName, importSymbols)
  262. # Now get the class definition for the classes named in the DC
  263. # file.
  264. for i in range(dcFile.getNumClasses()):
  265. dclass = dcFile.getClass(i)
  266. number = dclass.getNumber()
  267. className = dclass.getName() + self.dcSuffix
  268. # Does the class have a definition defined in the newly
  269. # imported namespace?
  270. classDef = dcImports.get(className)
  271. if classDef is None and self.dcSuffix == 'UD': #HACK:
  272. className = dclass.getName() + 'AI'
  273. classDef = dcImports.get(className)
  274. # Also try it without the dcSuffix.
  275. if classDef == None:
  276. className = dclass.getName()
  277. classDef = dcImports.get(className)
  278. if classDef is None:
  279. self.notify.debug("No class definition for %s." % (className))
  280. else:
  281. if type(classDef) == types.ModuleType:
  282. if not hasattr(classDef, className):
  283. self.notify.warning("Module %s does not define class %s." % (className, className))
  284. continue
  285. classDef = getattr(classDef, className)
  286. if type(classDef) != types.ClassType and type(classDef) != types.TypeType:
  287. self.notify.error("Symbol %s is not a class name." % (className))
  288. else:
  289. dclass.setClassDef(classDef)
  290. self.dclassesByName[className] = dclass
  291. if number >= 0:
  292. self.dclassesByNumber[number] = dclass
  293. # Owner Views
  294. if self.hasOwnerView():
  295. ownerDcSuffix = self.dcSuffix + 'OV'
  296. # dict of class names (without 'OV') that have owner views
  297. ownerImportSymbols = {}
  298. # Now import all of the modules required by the DC file.
  299. for n in range(dcFile.getNumImportModules()):
  300. moduleName = dcFile.getImportModule(n)
  301. # Maybe the module name is represented as "moduleName/AI".
  302. suffix = moduleName.split('/')
  303. moduleName = suffix[0]
  304. suffix=suffix[1:]
  305. if ownerDcSuffix in suffix:
  306. moduleName = moduleName + ownerDcSuffix
  307. importSymbols = []
  308. for i in range(dcFile.getNumImportSymbols(n)):
  309. symbolName = dcFile.getImportSymbol(n, i)
  310. # Check for the OV suffix
  311. suffix = symbolName.split('/')
  312. symbolName = suffix[0]
  313. suffix=suffix[1:]
  314. if ownerDcSuffix in suffix:
  315. symbolName += ownerDcSuffix
  316. importSymbols.append(symbolName)
  317. ownerImportSymbols[symbolName] = None
  318. self.importModule(dcImports, moduleName, importSymbols)
  319. # Now get the class definition for the owner classes named
  320. # in the DC file.
  321. for i in range(dcFile.getNumClasses()):
  322. dclass = dcFile.getClass(i)
  323. if ((dclass.getName()+ownerDcSuffix) in ownerImportSymbols):
  324. number = dclass.getNumber()
  325. className = dclass.getName() + ownerDcSuffix
  326. # Does the class have a definition defined in the newly
  327. # imported namespace?
  328. classDef = dcImports.get(className)
  329. if classDef is None:
  330. self.notify.error("No class definition for %s." % className)
  331. else:
  332. if type(classDef) == types.ModuleType:
  333. if not hasattr(classDef, className):
  334. self.notify.error("Module %s does not define class %s." % (className, className))
  335. classDef = getattr(classDef, className)
  336. dclass.setOwnerClassDef(classDef)
  337. self.dclassesByName[className] = dclass
  338. def importModule(self, dcImports, moduleName, importSymbols):
  339. """
  340. Imports the indicated moduleName and all of its symbols
  341. into the current namespace. This more-or-less reimplements
  342. the Python import command.
  343. """
  344. module = __import__(moduleName, globals(), locals(), importSymbols)
  345. if importSymbols:
  346. # "from moduleName import symbolName, symbolName, ..."
  347. # Copy just the named symbols into the dictionary.
  348. if importSymbols == ['*']:
  349. # "from moduleName import *"
  350. if hasattr(module, "__all__"):
  351. importSymbols = module.__all__
  352. else:
  353. importSymbols = module.__dict__.keys()
  354. for symbolName in importSymbols:
  355. if hasattr(module, symbolName):
  356. dcImports[symbolName] = getattr(module, symbolName)
  357. else:
  358. raise StandardError, 'Symbol %s not defined in module %s.' % (symbolName, moduleName)
  359. else:
  360. # "import moduleName"
  361. # Copy the root module name into the dictionary.
  362. # Follow the dotted chain down to the actual module.
  363. components = moduleName.split('.')
  364. dcImports[components[0]] = module
  365. def getServerAddress(self):
  366. return self._serverAddress
  367. def connect(self, serverList,
  368. successCallback = None, successArgs = [],
  369. failureCallback = None, failureArgs = []):
  370. """
  371. Attempts to establish a connection to the server. May return
  372. before the connection is established. The two callbacks
  373. represent the two functions to call (and their arguments) on
  374. success or failure, respectively. The failure callback also
  375. gets one additional parameter, which will be passed in first:
  376. the return status code giving reason for failure, if it is
  377. known.
  378. """
  379. ## if self.recorder and self.recorder.isPlaying():
  380. ## # If we have a recorder and it's already in playback mode,
  381. ## # don't actually attempt to connect to a gameserver since
  382. ## # we don't need to. Just let it play back the data.
  383. ## self.notify.info("Not connecting to gameserver; using playback data instead.")
  384. ## self.connectHttp = 1
  385. ## self.tcpConn = SocketStreamRecorder()
  386. ## self.recorder.addRecorder('gameserver', self.tcpConn)
  387. ## self.startReaderPollTask()
  388. ## if successCallback:
  389. ## successCallback(*successArgs)
  390. ## return
  391. hasProxy = 0
  392. if self.checkHttp():
  393. proxies = self.http.getProxiesForUrl(serverList[0])
  394. hasProxy = (proxies != 'DIRECT')
  395. if hasProxy:
  396. self.notify.info("Connecting to gameserver via proxy list: %s" % (proxies))
  397. else:
  398. self.notify.info("Connecting to gameserver directly (no proxy).")
  399. #Redefine the connection to http or net in the default case
  400. self.bootedIndex = None
  401. self.bootedText = None
  402. if self.connectMethod == self.CM_HTTP:
  403. # In the HTTP case, we can't just iterate through the list
  404. # of servers, because each server attempt requires
  405. # spawning a request and then coming back later to check
  406. # the success or failure. Instead, we start the ball
  407. # rolling by calling the connect callback, which will call
  408. # itself repeatedly until we establish a connection (or
  409. # run out of servers).
  410. ch = self.http.makeChannel(0)
  411. self.httpConnectCallback(
  412. ch, serverList, 0,
  413. successCallback, successArgs,
  414. failureCallback, failureArgs)
  415. elif self.connectMethod == self.CM_NET or (not hasattr(self,"connectNative")):
  416. # Try each of the servers in turn.
  417. for url in serverList:
  418. self.notify.info("Connecting to %s via NET interface." % (url.cStr()))
  419. if self.tryConnectNet(url):
  420. self.startReaderPollTask()
  421. if successCallback:
  422. successCallback(*successArgs)
  423. return
  424. # Failed to connect.
  425. if failureCallback:
  426. failureCallback(0, '', *failureArgs)
  427. elif self.connectMethod == self.CM_NATIVE:
  428. for url in serverList:
  429. self.notify.info("Connecting to %s via Native interface." % (url.cStr()))
  430. if self.connectNative(url):
  431. self.startReaderPollTask()
  432. if successCallback:
  433. successCallback(*successArgs)
  434. return
  435. # Failed to connect.
  436. if failureCallback:
  437. failureCallback(0, '', *failureArgs)
  438. else:
  439. print "uh oh, we aren't using one of the tri-state CM variables"
  440. failureCallback(0, '', *failureArgs)
  441. def disconnect(self):
  442. """
  443. Closes the previously-established connection.
  444. """
  445. self.notify.info("Closing connection to server.")
  446. self._serverAddress = ''
  447. CConnectionRepository.disconnect(self)
  448. self.stopReaderPollTask()
  449. def shutdown(self):
  450. self.ignoreAll()
  451. CConnectionRepository.shutdown(self)
  452. def httpConnectCallback(self, ch, serverList, serverIndex,
  453. successCallback, successArgs,
  454. failureCallback, failureArgs):
  455. if ch.isConnectionReady():
  456. self.setConnectionHttp(ch)
  457. self._serverAddress = serverList[serverIndex-1]
  458. ## if self.recorder:
  459. ## # If we have a recorder, we wrap the connect inside a
  460. ## # SocketStreamRecorder, which will trap incoming data
  461. ## # when the recorder is set to record mode. (It will
  462. ## # also play back data when the recorder is in playback
  463. ## # mode, but in that case we never get this far in the
  464. ## # code, since we just create an empty
  465. ## # SocketStreamRecorder without actually connecting to
  466. ## # the gameserver.)
  467. ## stream = SocketStreamRecorder(self.tcpConn, 1)
  468. ## self.recorder.addRecorder('gameserver', stream)
  469. ## # In this case, we pass ownership of the original
  470. ## # connection to the SocketStreamRecorder object.
  471. ## self.tcpConn.userManagesMemory = 0
  472. ## self.tcpConn = stream
  473. self.startReaderPollTask()
  474. if successCallback:
  475. successCallback(*successArgs)
  476. elif serverIndex < len(serverList):
  477. # No connection yet, but keep trying.
  478. url = serverList[serverIndex]
  479. self.notify.info("Connecting to %s via HTTP interface." % (url.cStr()))
  480. ch.preserveStatus()
  481. ch.beginConnectTo(DocumentSpec(url))
  482. ch.spawnTask(name = 'connect-to-server',
  483. callback = self.httpConnectCallback,
  484. extraArgs = [ch, serverList, serverIndex + 1,
  485. successCallback, successArgs,
  486. failureCallback, failureArgs])
  487. else:
  488. # No more servers to try; we have to give up now.
  489. if failureCallback:
  490. failureCallback(ch.getStatusCode(), ch.getStatusString(),
  491. *failureArgs)
  492. def checkHttp(self):
  493. # Creates an HTTPClient, if possible, if we don't have one
  494. # already. This might fail if the OpenSSL library isn't
  495. # available. Returns the HTTPClient (also self.http), or None
  496. # if not set.
  497. if self.http == None:
  498. try:
  499. self.http = HTTPClient()
  500. except:
  501. pass
  502. return self.http
  503. def startReaderPollTask(self):
  504. # Stop any tasks we are running now
  505. self.stopReaderPollTask()
  506. self.accept(CConnectionRepository.getOverflowEventName(),
  507. self.handleReaderOverflow)
  508. self.readerPollTaskObj = taskMgr.add(
  509. self.readerPollUntilEmpty, self.uniqueName("readerPollTask"),
  510. priority = self.taskPriority, taskChain = self.taskChain)
  511. def stopReaderPollTask(self):
  512. if self.readerPollTaskObj:
  513. taskMgr.remove(self.readerPollTaskObj)
  514. self.readerPollTaskObj = None
  515. self.ignore(CConnectionRepository.getOverflowEventName())
  516. def readerPollUntilEmpty(self, task):
  517. while self.readerPollOnce():
  518. pass
  519. return Task.cont
  520. def readerPollOnce(self):
  521. if self.checkDatagram():
  522. self.getDatagramIterator(self.private__di)
  523. self.handleDatagram(self.private__di)
  524. return 1
  525. # Unable to receive a datagram: did we lose the connection?
  526. if not self.isConnected():
  527. self.stopReaderPollTask()
  528. messenger.send(self.uniqueName('lostConnection'), taskChain = 'default')
  529. return 0
  530. def handleReaderOverflow(self):
  531. # this is called if the incoming-datagram queue overflowed and
  532. # we lost some data. Override and handle if desired.
  533. pass
  534. def lostConnection(self):
  535. # This should be overrided by a derived class to handle an
  536. # unexpectedly lost connection to the gameserver.
  537. self.notify.warning("Lost connection to gameserver.")
  538. def handleDatagram(self, di):
  539. # This class is meant to be pure virtual, and any classes that
  540. # inherit from it need to make their own handleDatagram method
  541. pass
  542. def send(self, datagram):
  543. # Zero-length datagrams might freak out the server. No point
  544. # in sending them, anyway.
  545. if datagram.getLength() > 0:
  546. if self.notify.getDebug():
  547. print "ConnectionRepository sending datagram:"
  548. datagram.dumpHex(ostream)
  549. self.sendDatagram(datagram)
  550. # debugging funcs for simulating a network-plug-pull
  551. def pullNetworkPlug(self):
  552. self.notify.warning('*** SIMULATING A NETWORK-PLUG-PULL ***')
  553. self.setSimulatedDisconnect(1)
  554. def networkPlugPulled(self):
  555. return self.getSimulatedDisconnect()
  556. def restoreNetworkPlug(self):
  557. if self.networkPlugPulled():
  558. self.notify.info('*** RESTORING SIMULATED PULLED-NETWORK-PLUG ***')
  559. self.setSimulatedDisconnect(0)
  560. def uniqueName(self, idString):
  561. return ("%s-%s" % (idString, self.uniqueId))
  562. class GCTrigger:
  563. # used to trigger garbage collection
  564. pass