VB.net TCP 是如何发送文件的 , 给一个示例
时间: 2024-02-06 17:11:14 浏览: 204
下面是一个简单的 VB.NET TCP 发送文件的示例:
```vb.net
' 客户端发送文件
Private Sub SendFile(ByVal filePath As String)
Try
' 创建 TCP 客户端
Dim client As New TcpClient("127.0.0.1", 8888)
' 打开文件流
Dim fileStream As New FileStream(filePath, FileMode.Open, FileAccess.Read)
' 获取文件名
Dim fileName As String = Path.GetFileName(filePath)
' 创建写入器
Dim writer As New BinaryWriter(client.GetStream())
' 发送文件名
writer.Write(fileName)
' 发送文件长度
writer.Write(fileStream.Length)
' 发送文件内容
Dim buffer(4096) As Byte
Dim bytesRead As Integer
Do
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
writer.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
' 关闭流和连接
fileStream.Close()
writer.Close()
client.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
' 服务器接收文件
Private Sub ReceiveFile()
Try
' 创建 TCP 服务器
Dim server As TcpListener = New TcpListener(IPAddress.Any, 8888)
server.Start()
Console.WriteLine("等待客户端连接...")
' 接受客户端连接
Dim client As TcpClient = server.AcceptTcpClient()
Console.WriteLine("客户端已连接...")
' 创建读取器
Dim reader As New BinaryReader(client.GetStream())
' 读取文件名
Dim fileName As String = reader.ReadString()
' 读取文件长度
Dim fileLength As Long = reader.ReadInt64()
' 创建文件流
Dim fileStream As New FileStream(fileName, FileMode.Create, FileAccess.Write)
' 读取文件内容
Dim buffer(4096) As Byte
Dim bytesRead As Integer
Do
bytesRead = reader.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
fileStream.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
' 关闭流和连接
fileStream.Close()
reader.Close()
client.Close()
server.Stop()
Console.WriteLine("文件接收完毕。")
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
```
在此示例中,客户端首先连接到服务器,然后将文件名、文件长度和文件内容依次发送给服务器。服务器接收到数据后,创建文件并将文件内容写入文件中,最后关闭连接。
阅读全文