gpt4 book ai didi

c# - 从 OnOpen 事件发送时未收到消息

转载 作者:行者123 更新时间:2023-12-03 12:07:33 24 4
gpt4 key购买 nike

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

我已经设置了一个 Controller :

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"));
}
}

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

我的网络客户端:

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);
});

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

网络选项卡中 -> 框架:
Network tab, Frames

我可以通过推迟对 System.Threading.TimerSendToAll 调用并设置一定的超时时间来解决此问题。我的调试显示,50ms 不一致,所以我将其设置为 300ms,看起来工作正常,但计时器感觉很糟糕。

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

最佳答案

3.0.6 中出现这种情况的原因是它完全与发布和订阅有关。

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

xs.on("notify",callback);

当 OnOpen 发生时,未绑定(bind)在服务器上...因此客户端连接将无法获取有关其自己连接的信息。

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

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

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

您将在第一个回调中调用服务器方法来通知其他人...

2在发送信息之前在服务器上进行绑定(bind),这可能是一个更简单的选择。

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 使用 XSockets.NET 4.0 BETA,它改进了通信并允许 RPC 或 Pub/Sub。在 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/

//示例中可能有拼写错误...这是我从头开始写的...

关于c# - 从 OnOpen 事件发送时未收到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25114242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com