//receive packet and write it static void ReceiveFile(DataFileSend f) { FileStream fs = new FileStream(Program.incomingFolder + f.fileinfo.name, FileMode.OpenOrCreate); fs.Position = f.position; fs.Write(f.data, 0, f.data.Length); fs.Close(); }
// Processing Data objects received static void HandleData(Data data) { if (data.type == DataType.FileSearch) { DataFileSearch dfs = (DataFileSearch)data; Console.WriteLine("[+] Received search for " + dfs.search); String[] tabFile = Directory.GetFiles(Program.incomingFolder, dfs.search); for (int i = 0; i < tabFile.Length; i++) { tabFile[i] = Path.GetFileName(tabFile[i]); } SendData(new DataFileResults { results = tabFile }); } else if (data.type == DataType.FileResults) { DataFileResults dfr = (DataFileResults)data; Console.WriteLine("[+] Received this results : "); for (int i = 0; i < dfr.results.Length; i++) { Console.WriteLine("- " + dfr.results[i]); } } else if (data.type == DataType.FileRequest) { DataFileRequest dfr = (DataFileRequest)data; sFile f = new sFile(incomingFolder + dfr.request); SendFile(f); Console.WriteLine("[+] Peer requested for " + dfr.request + ", file sent"); } else if (data.type == DataType.FileSend) { DataFileSend dfs = (DataFileSend)data; ReceiveFile(dfs); //BASIC check //since TCP is reliable, there should be no problem. But you can add checksum for integrity if (dfs.fileinfo.size == new FileInfo(incomingFolder + dfs.fileinfo.name).Length) { Console.WriteLine("[+] Received " + dfs.fileinfo.name); } } }