Skip to content

asyncio支持

实验性功能

远程call支持 async ,如下:

py
async def fetch_data():
    await asyncio.sleep(2)  # 模拟I/O操作
    print("success")

案例( http server )

在baseapp中启动http server

创建venv虚拟环境

参考 VENV虚拟环境 章节

安装 aiohttp

在虚拟环境中执行命令

bash
pip install aiohttp

或者在pycharm中 设置 -> Python -> 解释器 中安装 aiohttp

编写http server代码

  1. server_common文件夹中新建http_server.py
python
# -*- coding: utf-8 -*-
import asyncio
from aiohttp import web
import KBEngine


app = web.Application()

# 路由
async def handle(request):
    return web.Response(text="Hello KBEngine HTTP Server")


async def getEntities(request):
    entities_data = []

    for eid, entity in KBEngine.entities.items():
        entities_data.append({
            "id": eid,
            "class": entity.__class__.__name__,
        })

    return web.json_response({"count": len(entities_data), "entities": entities_data})


app.router.add_get("/", handle)
app.router.add_get("/getEntities", getEntities)



# HTTP 服务启动函数
async def start_http_server(host="0.0.0.0", port=8001):
    """
    启动 aiohttp 非阻塞 HTTP 服务
    """
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, host, port)
    await site.start()
    print(f"[HTTP] Server started on http://{host}:{port}")
  1. 在baseapp中的入口脚本(kbemain.py)中,导入并启动http server

TIP

此处只是提供asyncio的使用案例,http server更建议放在interface app中

python
# -*- coding: utf-8 -*-
import asyncio

import KBEngine
import Watcher
import d_spaces
from KBEDebug import *

from http_server import start_http_server  # 引入独立模块

async def onBaseAppReady(isBootstrap):
	"""
	KBEngine method.
	baseapp已经准备好了
	@param isBootstrap: 是否为第一个启动的baseapp
	@type isBootstrap: BOOL
	"""
	INFO_MSG('onBaseAppReady: isBootstrap=%s' % isBootstrap)
	
	# 安装监视器
	Watcher.setup()

	if isBootstrap:
		# 创建spacemanager
		KBEngine.createEntityLocally( "Spaces", {} )

		# 启动 aiohttp HTTP 服务(非阻塞)
		asyncio.create_task(start_http_server())

		INFO_MSG("aiohttp HTTP server 已启动(非阻塞)")

启动服务器

执行 start_server.shstart_server.bat 启动baseapp

访问http接口

在浏览器中访问http://127.0.0.0:8001/

在浏览器中访问http://127.0.0.0:8001/getEntities

系统回调:

WARNING

警告:请勿乱用async ,在不了解引擎执行顺序、async 原理、系统回调时机的情况下,禁止使用async ,会造成意想不到的BUG或系统负担

警告:带有返回值的回调方法一律无法使用async ,切记!!

警告:cellapp下,一切与时间、空间相关的回调请谨慎使用async ,会有时序问题


interfaces :

KBEngine:

  • [x] onInterfaceAppReady
  • [x] onRequestCreateAccount
  • [x] onRequestAccountLogin
  • [x] onRequestCharge
  • [x] onInit
  • [x] onInterfaceAppShutDown

base:

KBEngine:

  • [x] onGlobalDataDel
  • [x] onGlobalData
  • [x] onBaseAppDataDel
  • [x] onBaseAppData
  • [x] onInit
  • [x] onCellAppDeath
  • [x] onLoseChargeCB
  • [x] onAutoLoadEntityCreate
  • [x] onBaseAppReady
  • [x] onBaseAppShutDown
  • [ ] onReadyForLogin 不支持
  • [ ] onReadyForShutDown 不支持

Entity:

  • [x] onDestroy
  • [x] onCreateCellFailure
  • [x] onGetCell
  • [x] onClientDeath
  • [x] onLoseCell
  • [x] onRestore
  • [ ] onPreArchive 不支持
  • [x] onWriteToDB
  • [x] onTeleportFailure
  • [x] onTeleportSuccess
  • [x] onTimer

Proxy:

  • [x] onClientEnabled
  • [ ] onLogOnAttempt 不支持
  • [x] onClientDeath
  • [x] onClientGetCell
  • [x] onGiveClientToFailure
  • [x] onStreamComplete

EntityComponent:

  • [x] onAttached
  • [x] onDetached

cell:

KBEngine:

  • [x] onGlobalDataDel
  • [x] onGlobalData
  • [x] onCellAppDataDel
  • [x] onCellAppData
  • [x] onInit

Entity:

  • [x] onDestroy
  • [x] onSpaceGone
  • [x] onWriteToDB
  • [x] onWitnessed
  • [x] onLoseControlledBy
  • [x] onEnterTrap
  • [x] onLeaveTrap
  • [x] onEnteredView
  • [x] onGetWitness
  • [x] onLoseWitness
  • [x] onMove
  • [x] onMoveOver
  • [x] onMoveFailure
  • [x] onTurn
  • [x] onTeleport
  • [x] onTeleportFailure
  • [x] onTeleportSuccess
  • [x] onEnterSpace
  • [x] onLeaveSpace
  • [x] onEnteredCell
  • [x] onEnteringCell
  • [x] onLeavingCell
  • [x] onLeftCell
  • [x] onRestore
  • [x] onTimer
  • [ ] onReadyForLogin 不支持
  • [x] onSpaceGeometryLoaded
  • [x] onAllSpaceGeometryLoaded
  • [x] onSpaceData
  • [x] onUpdateBegin
  • [x] onUpdateEnd

login:

  • [x] onLoginAppShutDown
  • [x] onLoseLogin
  • [x] onLoginAppReady
  • [ ] onRequestCreateAccount 不支持
  • [x] onCreateAccountCallbackFromDB
  • [ ] onRequestLogin 不支持
  • [x] onLoginCallbackFromDB

bots:

  • [x] onInit
  • [x] onFinish