ConnectionRepository.py 27 KB

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