private void EndReceive(IAsyncResult res) { var state = res.AsyncState as SocketReceiveBundle; var ep = new IPEndPoint(IPAddress.Any, Port); byte[] data = null; try { data = state.UdpClient.EndReceive(res, ref ep); } catch (ObjectDisposedException ex) { Log.Info($"{nameof(EndReceive)}: This is more or less expected", ex); return; } if (data.Length < 4) { Receive(); return; } var length = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; if (data.Length < length) { Receive(); return; } data = data.Skip(4).ToArray(); try { using (var ms = new MemoryStream(data)) { ms.Position = 0; var bf = new BinaryFormatter(); var hg = (HostedGame)bf.Deserialize(ms); if (hg.Host == "0.0.0.0") { hg.HostAddress = $"{ep.Address}:{hg.Port}"; } lock (GameCache) { if (GameCache.Contains(hg.Id.ToString())) { GameCache.Remove(hg.Id.ToString()); } GameCache.Add(hg.Id.ToString(), hg, DateTime.Now.AddSeconds(10)); if (_awaitingStart.TryGetValue(hg.Id, out var tcs)) { tcs.SetResult(hg); } } } } catch (Exception ex) { Log.Error($"{nameof(EndReceive)}: Error reading data", ex); } Receive(); }
private void EndReceive(IAsyncResult res) { try { var state = res.AsyncState as SocketReceiveBundle; var ep = new IPEndPoint(IPAddress.Any, Port); var data = state.UdpClient.EndReceive(res, ref ep); if (data.Length < 4) { return; } var length = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; if (data.Length < length) { return; } data = data.Skip(4).ToArray(); using (var ms = new MemoryStream(data)) { ms.Position = 0; var bf = new BinaryFormatter(); var hg = (IHostedGameData)bf.Deserialize(ms); hg.TimeStarted = hg.TimeStarted.ToLocalTime(); hg.IpAddress = ep.Address; lock (GameCache) { if (GameCache.Contains(hg.Id.ToString())) { GameCache.Remove(hg.Id.ToString()); } GameCache.Add(hg.Id.ToString(), hg, DateTime.Now.AddSeconds(10)); if (_awaitingStart.TryGetValue(hg.Id, out var tcs)) { tcs.SetResult(hg); } } } } catch (Exception e) { Log.Error("EndReceive", e); } finally { if (IsListening) { Receive(); } } }