private static void HandleFileGetRequest(UdpClient target) { IPEndPoint remoteIPEndPoint = null; Console.Write("Please enter a filepath\\filename: "); string name = Console.ReadLine(); FileMetadataPacket pack = new FileMetadataPacket(Constants.TYPE_FILE_REQUEST, 0, name.Length, Encoding.Default.GetBytes(name), 0); byte[] receivedBytes = null; bool sent = false; Stopwatch timeout = new Stopwatch(); byte[] backup = new byte[Constants.PACKET_SIZE]; while (!sent) { for (int i = 0; i < Constants.PACKET_SIZE; i++) { backup[i] = pack.MyPacketAsBytes[i]; } Utils.SendTo(target, backup); timeout.Restart(); while (timeout.ElapsedMilliseconds < Constants.PACKET_TIMEOUT_MILLISECONDS) { if (target.Available != 0) { receivedBytes = target.Receive(ref remoteIPEndPoint); if (Utils.VerifyChecksum(receivedBytes)) { if (receivedBytes[Constants.FIELD_TYPE] == Constants.TYPE_FILE_DELIVERY) { sent = true; } } } } } PingPong.SendAckTo(-1, target); bool success = false; while (!success) { AckPacket ack = new AckPacket(-1); Utils.SendTo(target, ack.MyPacketAsBytes); success = PingPong.ReceiveFileFrom(receivedBytes, target); } Console.WriteLine("File received successfully."); }
public static bool SendFileTo(string filename, UdpClient target) { FileInfo localMeta; byte[] fileNameAsBytes; int totalPackets; try { localMeta = new FileInfo(filename); fileNameAsBytes = Encoding.Default.GetBytes(filename); totalPackets = (int)localMeta.Length / Constants.PAYLOAD_SIZE; if ((int)localMeta.Length % Constants.PAYLOAD_SIZE != 0 || totalPackets < 1) { totalPackets++; } } catch (ArgumentException ex) { return false; } catch (FileNotFoundException ex) { throw new FileNotFoundException(); } FileMetadataPacket meta = new FileMetadataPacket(Constants.TYPE_FILE_DELIVERY, (int)localMeta.Length, filename.Length, fileNameAsBytes, totalPackets); sendUntilAck(meta, target); try { StreamReader localFile = new StreamReader(filename, Encoding.Default); for (int i = 0; i < totalPackets; i++) { char[] stagedPayload = new char[Constants.PAYLOAD_SIZE]; localFile.Read(stagedPayload, 0, Constants.PAYLOAD_SIZE); byte[] encoded = Encoding.Default.GetBytes(stagedPayload); DataPacket stagedPacket = new DataPacket(Encoding.Default.GetBytes(stagedPayload), i); sendUntilAck(stagedPacket, target); } localFile.Close(); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Insufficient permissions to access specified file: " + ex.Message); } catch (IOException ex) { } return true; }