Question

I'm coding an ascynchronous socket client for transferring files (following this Microsoft article) and notice that using BeginReceive corrupts the transfer because it adds a single Null character/chr(0) at the end of each packet. What could be causing this issue? I thought it might be the sending side, but I tested it with SendFile and had the same result.

In the Microsoft article it converts the bytes to an ASCII string and appends it to a StringBuilder. I want to save the bytes on-the-fly, so I barely modified the ReceiveCallback like so:

Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult)
    Dim state As StateObject = CType(ar.AsyncState, StateObject)
    Dim client As Socket = state.workSocket
    Dim bytesRead As Integer = client.EndReceive(ar)
    If bytesRead > 0 Then
        FileIO.FileSystem.WriteAllBytes(Application.StartupPath & "\test.exe", state.buffer, True)
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
    Else
        receiveDone.Set()
    End If
End Sub
Was it helpful?

Solution

The problem is a misconception on how Receive, or BeginReceive & EndReceive work.

When you call Receive and give it a buffer and a size, you are specifying the maximum amount of data to receive. It is the bytesRead that tells you how much you actually received. You need to only write that number of bytes to your output file, as only that portion of your buffer was populated with data.

See here for more details:

http://msdn.microsoft.com/en-us/library/w3xtz6a5

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top