raw_api_server
一个用于小型、简单套接字式 API 的 Dart 包
特点
- 声明式
- 轻量级
- 可扩展
- 通过请求中的一个
uint8确定操作
入门
首先在 pubspec.yaml 中添加 raw_api_server: dart pub add raw_api_server
用法
服务器
服务器的最基本实现如下所示
final server = RawApiServer(
port: <port>,
endpoints: [
...
],
);
await server.start();
endpoints 参数需要一个 ApiEndpoint 类型的列表。一个端点包含一个用于标识所需操作的 id,以及一个用于处理请求的函数。
final echoEndpoint = ApiEndpoint(
id: 0,
handler: (socket, args) {
final argsString = String.fromCharCodes(args);
socket.write('you said: ${argsString}');
}
);
上面的端点占用了 id = 0,因此任何 id = 0 的客户端请求都将被定向到我们的 echoEndpoint。此端点具有将客户端的参数回复给客户端的基本功能。
注意: 端点必须具有唯一的 id 值。
Client
存在一个非常基本的套接字包装器,用于 Dart 与 raw_api_server 的一些兼容性。
final client = RawApiClient(
port: <port>,
host: <host>,
onReceive: (socket, data) {
print('Client received: ${String.fromCharCodes(data)}');
}
);
await client.connect();
我们也可以使用客户端发起请求。请求的格式为 List<int>,其第一个值是端点 id。我们可以使用 ApiRequest 轻松构建这些请求。
final request = ApiRequest.fromUtf8(id: 0, stringArgs: 'hello!');
await client.sendRequest(request);