SDK TypeScript
iohao opened this issue · comments
渔民小镇 commented
SDK 的作用是为了方便各客户端与 ioGame 服务器对接,与游戏服务器交互。
SDK 整体来说封装了两种使用方式,分别是
- 主动请求方式:由客户端主动向服务器发起的请求。
- 监听回调方式;主要用于监听服务器的广播,当监听到广播时,会触发相应的回调方法。
主动请求方式
SDK 为主动请求的方式提供了两种编码风格,两者可以完成同样的工作,开发者可根据自身业务选择使用。
请求方式一,编码风格-1
该请求方式是非阻塞的,开发者可设置响应回调与错误回调;优点:简洁,一体化。
// 【请求-非阻塞】【编码风格1】。可设置响应回调与错误回调;优点:简洁,一体化
RequestCommand.ofString(cmdMerge, "hello").onCallback(result => {
result.log(`print-1 ${result.getInt()}`)
}).execute();
// 【请求-非阻塞】【编码风格1】。可设置响应回调与错误回调;优点:简洁,一体化
RequestCommand.ofString(cmdMerge, "hello").onCallback(result => {
// 请求回调
result.log(`print-1 ${result.getInt()}`)
}).onError(result => {
// 错误处理回调
result.log(`${result.getErrorInfo()}`);
}).execute();
请求方式二,编码风格-2
该请求方式是非阻塞的,使用 await Promise 机制实现;优点:可避免回调地狱。
// 【请求-非阻塞】【编码风格2】。使用 await Promise 机制;优点:可避免回调地狱
let result = await RequestCommand.ofAwaitString(cmdMerge, "hello");
result.log(`ofAwait-1 ${result.getString()}`);
// 【请求-非阻塞】【编码风格2】。使用 await Promise 机制;优点:可避免回调地狱
let result = await RequestCommand.ofAwaitString(cmdMerge, "hello");
if (result.hasError()) {
// 错误处理
result.log(`ErrorInfo ${result.getErrorInfo()}`);
}
result.log(`ofAwait-1 ${result.getString()}`);
更多示例
- onClickStudent 方法演示了,传递一个对象,接收一个对象。
- onClickStudentList 方法演示了,传递一个 int 值(协议碎片特性),接收服务器返回的列表。
onClickStudent() {
let student = root.proto.Student.encode({
age: 1,
name: "ioGame"
}).finish();
// 【请求-非阻塞】【编码风格1】。可设置响应回调与错误回调;优点:简洁,一体化
RequestCommand.of(cmdMerge, student).onCallback(result => {
let value = result.getValue(root.proto.Student.decode);
result.log(value);
}).execute();
}
onClickStudentList() {
// 【请求-非阻塞】【编码风格1】。可设置响应回调与错误回调;优点:简洁,一体化
// 查询 3 个学生
RequestCommand.ofInt(cmdMerge, 3).onCallback(result => {
// 拿到学生列表
let value = result.listValue(root.proto.Student.decode);
result.log(value);
}).execute();
}
广播监听
主要用于监听服务器的广播,当监听到广播时,会触发对应的回调方法。
ListenCommand.of(cmdMerge, 'BOSS 战广播').onCallback(result => {
result.log(`ofAwait-1 ${result.getString()}`);
});
协议碎片
SDK 封装了常用的协议碎片特性,开发者可以方便的传递及获取。
onClickBase() {
// int
RequestCommand.ofInt(cmdMergeInt, 1).onCallback(result => {
result.log(`cmdMergeInt ${result.getInt()}`);
}).execute();
// boolean
RequestCommand.ofBool(cmdMergeBoolean, true).onCallback(result => {
result.log(`cmdMergeBoolean ${result.getBool()}`);
}).execute();
// string
RequestCommand.ofString(cmdMergeString, "hello").onCallback(result => {
result.log(`cmdMergeString ${result.getString()}`);
}).execute();
// long
RequestCommand.ofLong(cmdMergeLong, 1).onCallback(result => {
result.log(`cmdMergeLong ${result.getLong()}`);
}).execute();
}
小结
SDK 整体来说封装了两种使用方式,分别是
- 主动请求方式:由客户端主动向服务器发起的请求。
- 监听回调方式;主要用于监听服务器的广播,当监听到广播时,会触发相应的回调方法。
SDK 为主动请求的方式提供了两种编码风格,两者可以完成同样的工作。简单的请求推荐使用风格1,如果业务较复杂,可能会千万回调地狱的,推荐使用风格2。
SDK 封装了常用的协议碎片特性,开发者可以方便的传递及获取。