vb.net发送文件
时间: 2023-08-24 17:02:39 浏览: 252
VB.NET发送文件可以使用Socket进行网络通信。首先,我们需要创建一个服务器端和一个客户端。
服务器端代码如下:
```vb.net
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Server
Public Shared Sub Main()
Dim serverIp As IPAddress = IPAddress.Parse("服务器IP地址")
Dim serverPort As Integer = 8888
' 创建服务器Socket
Dim serverSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
serverSocket.Bind(New IPEndPoint(serverIp, serverPort))
serverSocket.Listen(10)
Console.WriteLine("等待客户端连接...")
Dim clientSocket As Socket = serverSocket.Accept()
Console.WriteLine("客户端已连接")
' 读取文件
Dim filePath As String = "文件路径"
Dim fileBytes As Byte() = File.ReadAllBytes(filePath)
' 发送文件大小给客户端
Dim fileSize As Integer = fileBytes.Length
Dim fileSizeBytes As Byte() = BitConverter.GetBytes(fileSize)
clientSocket.Send(fileSizeBytes)
' 发送文件给客户端
clientSocket.Send(fileBytes)
Console.WriteLine("文件已发送")
' 关闭连接
clientSocket.Shutdown(SocketShutdown.Both)
clientSocket.Close()
serverSocket.Close()
Console.WriteLine("连接已关闭")
End Sub
End Class
```
客户端代码如下:
```vb.net
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Client
Public Shared Sub Main()
Dim serverIp As IPAddress = IPAddress.Parse("服务器IP地址")
Dim serverPort As Integer = 8888
' 创建客户端Socket
Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
clientSocket.Connect(New IPEndPoint(serverIp, serverPort))
' 接收服务器发送的文件大小
Dim fileSizeBytes(3) As Byte
clientSocket.Receive(fileSizeBytes)
Dim fileSize As Integer = BitConverter.ToInt32(fileSizeBytes, 0)
' 接收文件内容
Dim receivedBytes As Integer = 0
Dim buffer(1024) As Byte
Using fileStream As New FileStream("保存文件路径", FileMode.Create, FileAccess.Write)
While receivedBytes < fileSize
Dim bytesRead As Integer = clientSocket.Receive(buffer)
fileStream.Write(buffer, 0, bytesRead)
receivedBytes += bytesRead
End While
End Using
Console.WriteLine("文件已接收")
' 关闭连接
clientSocket.Shutdown(SocketShutdown.Both)
clientSocket.Close()
Console.WriteLine("连接已关闭")
End Sub
End Class
```
注意替换代码中的服务器IP地址、服务器端口、文件路径和保存文件路径为实际的值。服务器端首先等待客户端连接,然后读取要发送的文件并发送给客户端。客户端首先连接服务器,然后接收服务器发送的文件大小,最后按照文件大小逐步接收文件内容并保存到本地。
运行服务器端和客户端,即可完成文件的发送和接收过程。
阅读全文