在调用 Start 之前向 ServiceStack 的 ServerEventsClient 注册 displayName

Registering displayName with ServiceStack's ServerEventsClient before invoking Start

我正在我的应用程序中开发一个小型聊天实现,我希望在有人拥有 joined/left 频道以及那个人是谁时得到通知。

在客户端,我正在收听 OnJoinOnLeave,它们采用 ServerEventCommand 对象,以展示消息,但是 ServerEventCommand 对象我在客户端注册后,在服务器端填充了一些看似随机的属性。

我正在查看 ServerEventsClient 对象及其所有属性,但找不到在调用 Start().

之前设置我想要的属性的方法

displayName 不是您设置的 属性,它是由服务器发送的,用于识别哪些用户是 joining/leaving 您订阅的频道。它将包含用户的 UserName,或者如果您的 Auth Provider 不使用用户名(例如,使用电子邮件或身份证号码)它将使用用户会话的 DisplayName 属性 .

您需要在 Server Events Client before calling .start(), e.g using the TypeScript ServerEventsClient:

中注册事件处理程序
const channels = ["home"];
const client = new ServerEventsClient("/", channels, {
    handlers: {
        onConnect: (sub:ServerEventConnect) => {  // Successful SSE connection
            console.log("You've connected! welcome " + sub.displayName);
        },
        onJoin: (msg:ServerEventJoin) => {        // User has joined subscribed channel
            console.log("Welcome, " + msg.displayName);
        },
        onLeave: (msg:ServerEventLeave) => {      // User has left subscribed channel
            console.log(msg.displayName + " has left the building");
        },
    }).start(); 

只有在您开始订阅并订阅您的频道后,您才会收到任何事件。

频道订阅者

大多数服务器事件客户端还允许您获取用户列表,例如使用 TypeScript 客户端,您可以调用 getChannelSubscribers():

client.getChannelSubscribers()
    .then(users => users.forEach(x => 
        console.log(`#${x.userId} @${x.displayName} ${x.profileUrl} ${x.channels}`)));

或者您可以直接调用/event-subscribers来获取每个频道的用户列表,例如:

$.getJSON("/event-subscribers?channels={{ channels }}", function (users) {
});

示例聊天应用程序

作为参考,有许多用不同语言编写的简单应用程序,它们使用可用于创建简单聊天应用程序的不同服务器事件客户端:

JavaScript Client

TypeScript Client

C# Server Events Client

Java Client