我在 VB.Net 中创建了一个文件共享程序,但是当我尝试发送文件时,接收部分没有正确接收文件。只有我发送的文件的一部分。比如说,我发送了一个 100 MB 的文件,只会收到 10 MB。有时 22 KB、39MB 等。接收到的文件的大小并不总是相同的。你认为是什么导致了这个问题?我应该怎么做才能正确接收整个文件?
发送部分
Sub Main()
Dim ip As New IPEndPoint(IPAddress.Any, 8888)' Port Server
Dim sock As New Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)' Protocol type
sock.Bind(ip)
sock.Listen(100)
While True' Check Client Connection
Try
msg("Accept Client Connect")
Dim csock As Sockets.Socket = sock.Accept
Dim csend(1024 * 10000) As Byte
Dim path As String = "C:\Users\IT\Desktop\test\" ' Location to save file
Dim bLen As Integer = csock.Receive(csend) ' Byte Read Len
Dim fileLen As Integer = BitConverter.ToInt32(csend, 0) ' File Len
Dim fName As String = Encoding.ASCII.GetString(csend, 4, fileLen) ' File Name
msg("Start Receive....." & fName)
Dim bWrite As New BinaryWriter(File.Open(path + fName, FileMode.Append))
bWrite.Write(csend, 4 + fileLen, bLen - 4 - fileLen)
msg("File receiced and Save " & path)
bWrite.Close()
csock.Close()
Catch ex As Exception
msg(ex.Message)
End Try
End While
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
接收部分
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ipServer As IPAddress() = Dns.GetHostAddresses("127.0.0.1") ' IP Server
Dim ip As IPEndPoint = New IPEndPoint(ipServer(0), 8888)
Dim csock As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
Dim fName As String = TextBox1.Text
Dim path As String = TextBox2.Text
Dim fNameByte() As Byte = Encoding.ASCII.GetBytes(fName)
Dim fData() As Byte = File.ReadAllBytes(path & "\" & fName)
Dim cData(4 + fName.Length + fData.Length) As Byte
Dim fDataLen() As Byte = BitConverter.GetBytes(fNameByte.Length)
Try
fDataLen.CopyTo(cData, 0)
fNameByte.CopyTo(cData, 4)
fData.CopyTo(cData, 4 + fNameByte.Length)
csock.Connect(ip)
csock.Send(cData)
MsgBox("Success Send File ")
csock.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
TextBox2.Text = System.IO.Path.GetDirectoryName(OpenFileDialog1.FileName)
End If
End Sub