internal override void OnConnectionClosedInternalSynchronized(ConnectionClosedEventArgs args) { base.OnConnectionClosedInternalSynchronized(args); args.Connection.Dispose(); this.Connection = null; }
private protected override void OnDatagram(Datagram datagram, UdpNetEndpoint remoteEndpoint) { if (this.connections.TryGetValue(remoteEndpoint, out UdpConnection connection)) { connection.OnDatagram(datagram); return; } UdpConnection newConnection = this.CreateConnection(); try { newConnection.Init(remoteEndpoint, false); newConnection.OnDatagram(datagram); } catch (Exception ex) { logger.Warn($"Couldn't init connection {newConnection}. {ex}"); return; } if (!connections.TryAdd(remoteEndpoint, newConnection)) { newConnection.CloseImmidiately(DisconnectReason.Error); Logger.Error($"Couldn't add connection {newConnection}"); } }
public Task ConnectAsync(IPEndPoint endpoint) { if (this.Connection != null) { throw new ConnectionFailed(DisconnectReason.Error, "Already connected"); } DestroySocket(); Bind(new IPEndPoint(IPAddress.Any, 0)); var connection = CreateConnection(); Random rnd = new Random(); connection.Init(new UdpNetEndpoint(endpoint, (ushort)rnd.Next(0, ushort.MaxValue)), true); Connection = connection; return(connection.Connect()); }
internal async Task <SocketError> SendDatagramAsync(UdpConnection connection, Datagram datagram) { if (connection == null) { throw new ArgumentNullException(nameof(connection)); } if (datagram == null) { throw new ArgumentNullException(nameof(datagram)); } if (datagram.IsDisposed) { Logger.Error("Got disposed datagram on Send. Perhaps race condition"); return(SocketError.InvalidArgument); } if (configuration.ConnectionSimulation != null) { if (random.NextDouble() < configuration.ConnectionSimulation.PacketLoss) { Logger.Debug($"We're sending datadram to {connection.EndPoint.EndPoint}, but according to connection simulation rules we dropped it"); return(SocketError.Success); } int delay = configuration.ConnectionSimulation.GetHalfDelay(); if (delay > 0) { await Task.Delay(delay).ConfigureAwait(false); } } SendDatagramAsyncResult operationInfo = new SendDatagramAsyncResult(connection, datagram); SocketAsyncEventArgs arg = socketArgsPool.Pop(); int bytes = datagram.WriteTo(new ArraySegment <byte>(arg.Buffer, 0, arg.Buffer.Length)); arg.SetBuffer(arg.Buffer, 0, bytes); arg.RemoteEndPoint = connection.EndPoint.EndPoint; arg.UserToken = operationInfo; Logger.Debug($"Sending {datagram} to {arg.RemoteEndPoint}"); if (!socket.SendToAsync(arg)) { IO_Complete(this, arg); } return(await operationInfo.Task.ConfigureAwait(false)); }
public SendDatagramAsyncResult(UdpConnection connection, Datagram datagram) { this.Datagram = datagram; this.Connection = connection; this.tcs = new TaskCompletionSource <SocketError>(TaskCreationOptions.RunContinuationsAsynchronously); }