发送端
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Dim mysocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
'声明socket
Dim myipendponit As New IPEndPoint(IPAddress.Parse("IP地址"), 8888) '建立一个终结点
OpenFileDialog1.Filter = "Text files (*.txt)|*.txt"
OpenFileDialog1.InitialDirectory = "c:\"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fs As New IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.OpenOrCreate, IO.FileAccess.Read) '你所要传输的文件
Dim ssize(fs.Length - 1) As Byte
Dim br As New BinaryReader(fs) '处理要传输的文件
br.Read(ssize, 0, ssize.Length - 1)
mysocket.Connect(myipendponit) '连接到远程计算机
mysocket.Send(ssize) '发送文件
Label2.Text = fs.Length()
fs.Close()
mysocket.Shutdown(Net.Sockets.SocketShutdown.Send)
'关闭已发送连接
mysocket.Close() '关闭本机socket
接收端
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim hostipendpoint As New IPEndPoint(IPAddress.Parse("IP地址"), 8888)
receivesocket.Bind(hostipendpoint)
'建立远程计算机的的socket
receivesocket.Listen(2) '监听socket
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "Text files (*.txt)|*.txt"
SaveFileDialog1.FileName = "接收的文件.txt"
SaveFileDialog1.InitialDirectory = "c:\Mytext"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fs As New IO.FileStream(SaveFileDialog1.FileName, IO.FileMode.OpenOrCreate)
'接收数据并将其保存到一个新的文件
Dim rebyte(229888) As Byte
Dim myhostsocket As Socket = receivesocket.Accept()
'发送端计算机建立连接
Dim wr As New BinaryWriter(fs) '流写
myhostsocket.Receive(rebyte)
wr.Write(rebyte, 0, rebyte.Length - 1)
fs.Close()
myhostsocket.Shutdown(SocketShutdown.Receive)
myhostsocket.Close()
Label2.Text = SaveFileDialog1.FileName
'读取已保存的文件
Dim Readw As StreamReader
Readw = File.OpenText(SaveFileDialog1.FileName)
' 设置指针到开始位置
Readw.BaseStream.Seek(0, SeekOrigin.Begin)
Readw.BaseStream.Position = 0
While (Readw.Peek() > -1)
TextBox1.Text += Readw.ReadLine() & vbCrLf
End While
Readw.Close()
End If
End Sub