|
-
Dec 19th, 2011, 06:12 PM
#10
Thread Starter
Hyperactive Member
Re: Transfer file over network
 Originally Posted by jmcilhinney
Given that the FileInfo.Length property is type Int64, it would make sense to transmit the file size as a 64-bit number. You might look at using a BinaryWriter and BinaryReader, which will allow you to write/read both the number and the data directly, or else look at the BitConverter class for converting between numbers and byte arrays.
Yeah I have used the BitConverter. I used the byte[].Length to get the length of the file and then converted that int to byte[] with the BitConverter.
 Originally Posted by jmcilhinney
It should, should it? Did you actually read the documentation for that property? How do you suppose the Length property value is produced? All the bytes in the Stream would have to be counted, would they not? How can a NetworkStream count the bytes when they are on the other side of a network connection? If you cannot Seek randomly through a Stream then you cannot get its Length either.
Oh I see. Well I recently discovered the Seek method and wanted to use it, but yeah it doesn't work either.
I have written some code, though I am stuck in one (maybe more) place and probably need to rewrite something hehe.
Here is the new send part:
Code:
NetworkStream stream = tcpServer.GetStream();
byte[] fileData = File.ReadAllBytes("C:\\test.zip");
int length = fileData.Length;
byte[] fileLength = BitConverter.GetBytes(fileData.Length);
byte[] protocolID = BitConverter.GetBytes(1337);
byte[] sendData = new byte[8 + fileData.Length];
protocolID.CopyTo(sendData, 0);
fileLength.CopyTo(sendData, 4);
fileData.CopyTo(sendData, 8);
stream.Write(sendData, 0, sendData.Length);
Which I think looks quite nice (of course I will make it more "safe" when I am done).
But when it comes to the reading part, I feel I have lost the control a bit:
Code:
NetworkStream stream = tcpClient.GetStream();
while (true) //Is there something better to replace true with? stream.DataAvailable won't work since it jumps out of the loop as soon as there is no data available.
{
byte[] info = new byte[8];
if (stream.Read(info, 0, 8) <= 0)
{
//Fail
}
int protocol = BitConverter.ToInt32(info, 0);
if (protocol != 1337)
{
//don't care about other protocols for now
continue;
}
int size = BitConverter.ToInt32(info, 4);
byte[] fileData = new byte[size];
if (stream.Read(fileData, 0, fileData.Length + 8) <= 0)
{
//Fail
}
File.WriteAllBytes("C:\\testTransf.zip", fileData.); //Here is the problem kinda, I only want to write the later part of the fileData (start from 8) but I have no idea how.
}
Also, the code doesn't seem that optimal, it feel quite dirty
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|