serverpod-server-events
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseServerpod Server Events
Serverpod Server Events
Event messaging via on named channels. Messages must be serializable models. By default () messages are delivered across the cluster when Redis is enabled, otherwise locally within the server instance.
session.messagesMessageScope.auto通过在命名通道上进行事件消息传递。消息必须是可序列化的模型。默认情况下(),当Redis启用时,消息会在集群间传递,否则仅在服务器实例本地传递。
session.messagesMessageScope.autoSending
发送消息
dart
await session.messages.postMessage('user_updates', UserUpdate(...));
// Restrict delivery with a scope:
await session.messages.postMessage('user_updates', message, scope: MessageScope.local);
await session.messages.postMessage('user_updates', message, scope: MessageScope.global);MessageScope.localMessageScope.globalStateErrordart
await session.messages.postMessage('user_updates', UserUpdate(...));
// 通过作用域限制消息传递范围:
await session.messages.postMessage('user_updates', message, scope: MessageScope.local);
await session.messages.postMessage('user_updates', message, scope: MessageScope.global);MessageScope.localMessageScope.globalStateErrorReceiving
接收消息
Stream:
dart
var stream = session.messages.createStream<UserUpdate>('user_updates');
stream.listen((message) => print('Received: $message'));If a message on the channel is not of type , the stream emits an error. Use exact serializable types or a deliberate shared base type.
TListener:
dart
session.messages.addListener<UserUpdate>('user_updates', (message) {
print('Received: $message');
});Both receive local and global messages. Streams/listeners are removed when the session closes. Remove manually with . Models support inheritance, which is useful when wanting a fully typed interface for server events.
session.messages.removeListener(channel, callback)流方式:
dart
var stream = session.messages.createStream<UserUpdate>('user_updates');
stream.listen((message) => print('Received: $message'));如果通道中的消息类型不是,流会抛出错误。请使用精确的可序列化类型或明确的共享基类。
T监听器方式:
dart
session.messages.addListener<UserUpdate>('user_updates', (message) {
print('Received: $message');
});两种方式都会接收本地和全局消息。当会话关闭时,流/监听器会被自动移除。也可以通过手动移除。模型支持继承,这在为服务器事件提供全类型化接口时非常有用。
session.messages.removeListener(channel, callback)