我有一个连接到 NATS 服务以发送和接受 NATS 消息的 C# 应用程序。它在一段时间内运行良好。但是,我需要建立一些逻辑,如果 NATS 服务停止,我会采取行动让用户知道我们无法发送或接收消息。我查看了互联网上的示例并相应地应用了它,但是在测试时我没有看到任何响应,好像事件没有被触发一样。当我停止 NATS 服务时,我期待事件触发并显示一条消息。谁能告诉我我错过了什么?
private void OpenNatsConnections()
{
LocalLog("Opening connection to Nats");
// Setup connection options
Options Opts = ConnectionFactory.GetDefaultOptions();
Opts.Url = appSettings.GetNatsUrl();
Opts.User = appSettings.NATSUsername;
Opts.Password = appSettings.NATSPassword;
Opts.AsyncErrorEventHandler += (sender, args) =>
{
LocalLog("AsyncErrorEventHandler");
};
Opts.ClosedEventHandler += (sender, args) =>
{
LocalLog("ClosedEventHandler");
};
Opts.DisconnectedEventHandler += (sender, args) =>
{
LocalLog("DisconnectedEventHandler");
};
// Open Nats connection, assign event handeler and subscribe to listening channel
try
{
NATSConnection = new ConnectionFactory().CreateConnection(Opts);
AsyncNATSMessageHandler = (sender, args) =>
{
string MessageData = Encoding.ASCII.GetString(args.Message.Data);
DetermineMessageType(MessageData, args.Message.Reply);
};
SubscribeToNATS();
LocalLog("Connected to Nats");
}
catch (Exception e)
{
LocalLog("Critical!! Connection to NATS failed! Error Message - " + e.Message);
}
}