25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

50 lines
1.3 KiB

  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Server;
  5. using Newtonsoft.Json;
  6. namespace MQTTnet.TestApp.UniversalWindows
  7. {
  8. public class JsonServerStorage : IMqttServerStorage
  9. {
  10. private readonly string _filename = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Retained.json");
  11. public async Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  12. {
  13. await Task.CompletedTask;
  14. var json = JsonConvert.SerializeObject(messages);
  15. File.WriteAllText(_filename, json);
  16. }
  17. public async Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  18. {
  19. await Task.CompletedTask;
  20. if (!File.Exists(_filename))
  21. {
  22. return new List<MqttApplicationMessage>();
  23. }
  24. try
  25. {
  26. var json = File.ReadAllText(_filename);
  27. return JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
  28. }
  29. catch
  30. {
  31. return new List<MqttApplicationMessage>();
  32. }
  33. }
  34. public void Clear()
  35. {
  36. if (File.Exists(_filename))
  37. {
  38. File.Delete(_filename);
  39. }
  40. }
  41. }
  42. }