serverpod-server-events

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Serverpod Server Events

Serverpod Server Events

Event messaging via
session.messages
on named channels. Messages must be serializable models. By default (
MessageScope.auto
) messages are delivered across the cluster when Redis is enabled, otherwise locally within the server instance.
通过
session.messages
在命名通道上进行事件消息传递。消息必须是可序列化的模型。默认情况下(
MessageScope.auto
),当Redis启用时,消息会在集群间传递,否则仅在服务器实例本地传递。

Sending

发送消息

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.local
delivers synchronously within this server only.
MessageScope.global
requires Redis and throws a
StateError
if it is not enabled. With Redis enabled, delivery is asynchronous and best effort, and listeners receive a deserialized copy of the message rather than the posted instance.
dart
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.local
仅在当前服务器内同步传递消息。
MessageScope.global
需要Redis支持,如果未启用Redis会抛出
StateError
。当Redis启用时,消息传递是异步且尽力而为的,监听器会接收消息的反序列化副本而非发布的实例。

Receiving

接收消息

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
T
, the stream emits an error. Use exact serializable types or a deliberate shared base type.
Listener:
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
session.messages.removeListener(channel, callback)
. Models support inheritance, which is useful when wanting a fully typed interface for server events.
流方式:
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)
手动移除。模型支持继承,这在为服务器事件提供全类型化接口时非常有用。