BeginReceive尾随空字符/ chr(0)

时间:2012-09-12 10:40:24

标签: vb.net sockets null beginreceive

我正在为传输文件(following this Microsoft article)编写一个ascynchronous套接字客户端,并注意到使用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

1 个答案:

答案 0 :(得分:1)

问题是对ReceiveBeginReceive& EndReceive工作。

当您致电Receive并为其指定缓冲区和大小时,您指定要接收的最大数据量。 bytesRead告诉您实际接收的数量。{{1}}。您只需要将这个字节数写入输出文件,因为只有缓冲区的那部分填充了数据。

请点击此处了解更多详情:

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