/// <summary> /// Called when a new UDP packet is received on the listening port. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UdpMessageReceived(object sender, SocketAsyncEventArgs e) { //Copy over buffer and remote endpoint bool completingAsync; do { using (MessageBuffer buffer = MessageBuffer.Create(e.BytesTransferred)) { Buffer.BlockCopy(e.Buffer, 0, buffer.Buffer, buffer.Offset, e.BytesTransferred); buffer.Count = e.BytesTransferred; EndPoint remoteEndPoint = e.RemoteEndPoint; //Start listening again try { completingAsync = UdpListener.ReceiveFromAsync(e); } catch (ObjectDisposedException) { return; } //Handle message or new connection BichannelServerConnection connection; bool exists; lock (UdpConnections) // TODO remove lock please exists = UdpConnections.TryGetValue(remoteEndPoint, out connection); if (exists) { connection.HandleUdpMessage(buffer); } else { HandleUdpConnection(buffer, remoteEndPoint); } } }while (!completingAsync); }
/// <summary> /// Called when a UDP message is received on the fallback system. /// </summary> /// <param name="result">The result of the operation.</param> private void UdpMessageReceived(IAsyncResult result) { EndPoint remoteEndPoint = new IPEndPoint(Address.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0); int bytesReceived; try { bytesReceived = UdpListener.EndReceiveFrom(result, ref remoteEndPoint); } catch (SocketException) { UdpListener.BeginReceiveFrom((byte[])result.AsyncState, 0, ushort.MaxValue, SocketFlags.None, ref remoteEndPoint, UdpMessageReceived, (byte[])result.AsyncState); return; } //Copy over buffer and remote endpoint using (MessageBuffer buffer = MessageBuffer.Create(bytesReceived)) { Buffer.BlockCopy((byte[])result.AsyncState, 0, buffer.Buffer, buffer.Offset, bytesReceived); buffer.Count = bytesReceived; //Start listening again UdpListener.BeginReceiveFrom((byte[])result.AsyncState, 0, ushort.MaxValue, SocketFlags.None, ref remoteEndPoint, UdpMessageReceived, (byte[])result.AsyncState); //Handle message or new connection BichannelServerConnection connection; bool exists; lock (UdpConnections) exists = UdpConnections.TryGetValue(remoteEndPoint, out connection); if (exists) { connection.HandleUdpMessage(buffer); } else { HandleUdpConnection(buffer, remoteEndPoint); } } }