简体   繁体   中英

C# socket programming problem [receive file has a different hash]

I have socket program which sends a file from socket client to socket server and create the file on the server

There is no problem in sending the file to the server ... [Not corrupted]

But,

Im my code : (Server listening and receive data )

this.buffer = new byte[1000000];
 this.DataSocket.Receive(this.buffer, this.buffer.Length, SocketFlags.None);

So always 1000000 bytes are received from the client to server which always the file created in the server has a fix size value .. also larger than the original file.

most fuzzy thing is file MD5 hashes are different... because of this fixed buffer as i think

my problem is how i cant send the file to the server with the same MD5 Hash ?

There's no need to go crazy on the buffer, you can read it in portions. You can also use a MemoryStream to hold all the collected information while you receive it in:

MemoryStream MemStream = new MemoryStream();
this.buffer = new byte[1024];

int BytesRead = this.DataSocket.Receive(this.buffer, this.buffer.Length, SocketFlags.None);
while (BytesRead > 0)
{
  MemStream.Write(this.buffer, 0, this.buffer.Length);
  BytesRead = this.DataSocket.Receive(this.buffer, this.buffer.Length, SocketFlags.None);
}

I think this may be because the MD5 is begin created with the entire buffer you have created. If the data is only 50000 bytes long but the buffer is 1000000 I assume these would create different hash values.

If I remember correctly the receive method returns an int which should be the size of the data that you have received. You could create a new byte array and copy the received data into an array which is the exact same size as the original file.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM