WingMan – Blame information for rev 35
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
5 | office | 1 | using System; |
2 | using System.IO; |
||
7 | office | 3 | using System.Threading; |
5 | office | 4 | using System.Threading.Tasks; |
5 | using WingMan.Communication; |
||
6 | |||
7 | office | 7 | namespace WingMan.Lobby |
5 | office | 8 | { |
9 | public class LobbyMessageSynchronizer : IDisposable |
||
10 | { |
||
11 | public delegate void LobbyMessageReceived(object sender, LobbyMessageReceivedEventArgs e); |
||
12 | |||
9 | office | 13 | public LobbyMessageSynchronizer(MqttCommunication mqttCommunication, TaskScheduler taskScheduler, |
7 | office | 14 | CancellationToken cancellationToken) |
5 | office | 15 | { |
9 | office | 16 | MqttCommunication = mqttCommunication; |
7 | office | 17 | CancellationToken = cancellationToken; |
18 | TaskScheduler = taskScheduler; |
||
5 | office | 19 | |
9 | office | 20 | mqttCommunication.OnMessageReceived += MqttCommunicationOnOnMessageReceived; |
5 | office | 21 | } |
22 | |||
9 | office | 23 | private MqttCommunication MqttCommunication { get; } |
7 | office | 24 | |
25 | private CancellationToken CancellationToken { get; } |
||
26 | private TaskScheduler TaskScheduler { get; } |
||
27 | |||
28 | public void Dispose() |
||
5 | office | 29 | { |
9 | office | 30 | MqttCommunication.OnMessageReceived -= MqttCommunicationOnOnMessageReceived; |
7 | office | 31 | } |
32 | |||
33 | public event LobbyMessageReceived OnLobbyMessageReceived; |
||
34 | |||
35 | private async void MqttCommunicationOnOnMessageReceived(object sender, |
||
35 | office | 36 | MqttCommunicationMessageReceivedEventArgs e) |
7 | office | 37 | { |
35 | office | 38 | if (e.Topic != "lobby") |
5 | office | 39 | return; |
40 | |||
35 | office | 41 | using (var memoryStream = new MemoryStream()) |
5 | office | 42 | { |
35 | office | 43 | await e.PayloadStream.CopyToAsync(memoryStream); |
44 | |||
45 | memoryStream.Position = 0L; |
||
46 | |||
7 | office | 47 | var lobbyMessage = (LobbyMessage) LobbyMessage.XmlSerializer.Deserialize(memoryStream); |
5 | office | 48 | |
7 | office | 49 | await Task.Delay(0) |
50 | .ContinueWith( |
||
51 | _ => OnLobbyMessageReceived?.Invoke(sender, |
||
52 | new LobbyMessageReceivedEventArgs(lobbyMessage.Nick, lobbyMessage.Message)), |
||
53 | CancellationToken, TaskContinuationOptions.None, TaskScheduler); |
||
5 | office | 54 | } |
55 | } |
||
56 | |||
57 | public async Task Broadcast(string message) |
||
58 | { |
||
59 | using (var memoryStream = new MemoryStream()) |
||
60 | { |
||
61 | LobbyMessage.XmlSerializer.Serialize(memoryStream, new LobbyMessage |
||
62 | { |
||
9 | office | 63 | Nick = MqttCommunication.Nick, |
5 | office | 64 | Message = message |
65 | }); |
||
66 | |||
67 | memoryStream.Position = 0L; |
||
68 | |||
10 | office | 69 | await MqttCommunication.Broadcast("lobby", memoryStream.ToArray()); |
5 | office | 70 | } |
71 | } |
||
72 | } |
||
35 | office | 73 | } |