ConnectionRepository.py 27 KB

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