我正在编写一个异步套接字客户端来传输文件(在这篇 Microsoft 文章之后),并注意到使用 BeginReceive 会破坏传输,因为它在每个数据包的末尾添加了一个 Null 字符/chr(0)。什么可能导致此问题?我认为它可能是发送方,但我用 SendFile 对其进行了测试并得到了相同的结果。
在 Microsoft 文章中,它将字节转换为 ASCII 字符串并将其附加到 StringBuilder。我想即时保存字节,所以我几乎没有像这样修改 ReceiveCallback:
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