我目前正在构建一个具有一些日志记录功能的文件传输应用程序。它的作用是,每次客户端连接或断开连接时,它都会向服务器发送日志(字符串消息)。日志记录部分工作正常,但是当我尝试发送文件时,程序会出错。
看来这纯粹是服务器端问题。发生的是以前的数据;这是用于记录的字符串消息,从客户端发送似乎卡在网络流上。当我在连接到服务器后尝试发送文件时,我收到一条错误消息,指出path 中的非法字符。
这是错误的屏幕截图。
我相信发生这种情况是因为,正如您在上面的屏幕截图中的FileName
变量中看到的那样,当客户端连接时发送的字符串的一部分(“已连接。”)卡在网络流上。hello.cpp 是正在发送的文件的名称。
这是代码。
Dim ClientSocket As TcpClient = CType(tcpSocket, TcpClient)
Dim networkStream As NetworkStream = ClientSocket.GetStream() 'This stream is
'for the logging part. This part here, I think causes the error because when I
'remove this and the conditions for the logging part, leaving the file sharing
'algorithm alone, the whole program works.
While FileSharingStarted
If CBool(ClientSocket.Available) Then
Dim ByteData(ClientSocket.ReceiveBufferSize) As Byte
networkStream.Read(ByteData, 0, CInt(ClientSocket.ReceiveBufferSize))
fileLogMessage = Encoding.ASCII.GetString(ByteData)
If fileLogMessage.Contains("is connected." & Environment.NewLine) Then
'This block here is for logging purposes. It receives the string
'message sent by the client when it connects and does some stuffs.
ElseIf fileLogMessage.Contains("is disconnected." & Environment.NewLine) Then
'This block here is for logging purposes again. It receives the
'string message sent by the client when it disconnects and then
'does some stuffs.
Else
'This part is for receiving the file sent by the client.
Dim FileName, FilePath As String
Dim FileLength As Long
Dim binaryReader As New BinaryReader(ClientSocket.GetStream())
FileName = binaryReader.ReadString()
FileLength = binaryReader.ReadInt64()
FilePath = Path.Combine(System.Environment.CurrentDirectory & "\home", FileName)
Dim FileData(8092) As Byte
Dim TotalData As Long = 0
Dim ReadBytes As Integer = -1
Using FileStream As New FileStream(FilePath, FileMode.Create, FileAccess.Write)
FileSharingStatusBar.Panels.Item(1).Text = "Receiving file . . ."
Do Until TotalData = FileLength
ReadBytes = ClientSocket.GetStream.Read(FileData, 0, FileData.Length())
FileStream.Write(FileData, 0, ReadBytes)
TotalData += ReadBytes
Loop
End Using
MessageBox.Show("File received.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
FileSharingStatusBar.Panels.Item(1).Text = "Idle."
End If
End If
End While
我只是好奇为什么会这样。我在这里错过了什么吗?任何解释或建议来解决这个问题都将受到高度赞赏。请赐教。:)