0

我正在使用 XSockets 3.x(最新)。

我已经设置了一个控制器:

public class NotificationsController : XSocketController
{
    public NotificationsController()
    {
        // Bind an event for once the connection has been opened.
        this.OnOpen += OnConnectionOpened;

        // Bind an event for once the connection has been closed.
        this.OnClose += OnConnectionClosed;
    }

    void OnConnectionOpened(object sender, XSockets.Core.Common.Socket.Event.Arguments.OnClientConnectArgs e)
    {
        // Notify everyone of the new client.
        this.SendToAll(new TextArgs("New client. Called right from OnConnectionOpened.", "notify"));
    }
}

可以看出,它只是一个基本的控制器,监听连接并在建立新连接后通知每个人,但是,它不起作用 - 没有收到消息。Chrome 的开发工具也没有显示任何框架。

我的网络客户端:

var xs = new XSockets.WebSocket("ws://" + window.location.hostname + ":1338/notifications");

xs.onopen = function(e)
{
    console.log("Connected", e);
};

xs.on('notify', function(data)
{
    console.log(data);
});

我在控制台中看到以下输出:
控制台输出

这在Network选项卡 -> Frames中:
网络选项卡,帧

SendToAll我可以通过将调用推迟到 a 来解决这个问题System.Threading.Timer。我的调试显示,50ms 不一致,所以我将它设置为 300ms,它似乎工作正常,但计时器感觉非常糟糕。

我该如何解决这个问题?
当 XSockets 真的为客户端准备好时,是否有我可以监听的事件?

4

1 回答 1

1

在 3.0.6 中这样做的原因是它完全是关于发布和订阅的。

这意味着消息只会发送到订阅了服务器上主题的客户端。在您提供的示例中,您似乎只有一个客户。此客户端将不会收到他自己的“通知”消息,因为绑定

xs.on("notify",callback);

OnOpen 发生时未绑定在服务器上...因此连接的客户端将不会获得有关他自己的连接的信息。

有几种方法可以解决这个问题......

1在绑定通知之前不要通知连接。这是通过向绑定添加第三个回调来完成的。当订阅绑定在服务器上时,将触发该回调。像这样

xs.on('notify', function(d){console.log('a connection was established')}, function(){console.log('the server has confirmed the notify subscription')});

您将在第一个回调中调用 servermethod 来通知其他人......

2在发送信息之前在服务器上进行绑定,这可能是一个令人窒息的选项。

void OnConnectionOpened(object sender, OnClientConnectArgs e)
{
    //Add the subscription
    this.Subscribe(new XSubscriptions{Event = "notify",Alias = this.Alias});
    // Notify everyone of the new client.
    this.SendToAll("New client. Called right from OnConnectionOpened.", "notify");
}

3使用改进了通信并允许 RPC 或 Pub/Sub 的 XSockets.NET 4.0 BETA。在 4.0 中,您会在 OnOpen 事件中这样做

//Send the message to all clients regardless of subscriptions or not...
this.InvokeToAll("New client. Called right from OnConnectionOpened.", "notify");

//Client side JavaScript
xs.controller('NotificationsController').on('notify', function(data){
    console.log(data);
});

//Client side C#
xs.Controller("NotificationsController").On<string>('notify', s => Console.WriteLine(s));

4.0 有很多其他重要的改进...如果您对 4.0 感兴趣,可以在这里阅读http://xsockets.github.io/XSockets.NET-4.0/

//可能是样本中的错别字...从我的头顶写在这里...

于 2014-08-04T19:48:19.957 回答