比如,用代码在指定的服务器里下载指定的文件到本地电脑上.
比如,用代码在指定的服务器里下载指定的文件到本地电脑上.
客户端:
Imports System.IO
Public Class frmMain
Inherits System.Windows.Forms.Form
Private Sub btn_Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Send.Click
If Not File.Exists(txt_FileName.Text) Then
MsgBox("找不到文件")
Exit Sub
End If
Try
Dim sendsocket As New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
''实例化socket
Dim ipendpiont As New Net.IPEndPoint(Net.IPAddress.Parse("192.168.106.123"), 8888) ''建立终结点
''OpenFileDialog1.ShowDialog()
Dim fs As New IO.FileStream(txt_FileName.Text, IO.FileMode.OpenOrCreate, IO.FileAccess.Read) ''要传输的文件
Dim fssize(fs.Length - 1) As Byte
Dim strread As New IO.BinaryReader(fs) ''流处理要传输的文件
''fs.Read(fssize, 0, fssize.Length - 1)
strread.Read(fssize, 0, fssize.Length - 1)
sendsocket.Connect(ipendpiont) ''连接远程计算机
sendsocket.Send(fssize) ''发送文件
Label1.Text = fs.Length()
fs.Close()
sendsocket.Shutdown(Net.Sockets.SocketShutdown.Send)
''关闭发送连接
sendsocket.Close() ''关闭本机socket
Catch ex As Exception
End Try
End Sub
Private Sub btn_Open_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Open.Click
If ofd_Open.ShowDialog = Windows.Forms.DialogResult.OK Then
txt_FileName.Text = ofd_Open.FileName
End If
End Sub
End Class
服务器:
Public Class frmMain
Inherits System.Windows.Forms.Form
Dim receivesocket As New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
Private Sub btn_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Save.Click
Try
If sfd_Save.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim strFileName As String = sfd_Save.FileName
txt_File.Text = strFileName
Dim recfs As New IO.FileStream(strFileName, IO.FileMode.OpenOrCreate)
''接收数据并将其保存到一个新的文件中
Dim recbyte(229888) As Byte
Dim hostsocket As Net.Sockets.Socket = receivesocket.Accept()
''同意和发送端计算机建立连接
Dim newfilestr As New IO.BinaryWriter(recfs) ''流写
hostsocket.Receive(recbyte)
''recfs.Write(recbyte, 0, recbyte.Length - 1)
newfilestr.Write(recbyte, 0, recbyte.Length - 1)
recfs.Close()
hostsocket.Shutdown(Net.Sockets.SocketShutdown.Receive)
hostsocket.Close()
End If
Catch ex As Exception
End Try
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim hostipendpiont As New Net.IPEndPoint(Net.IPAddress.Parse("192.168.1.123"), 8888)
receivesocket.Bind(hostipendpiont)
''建立远程计算机的的socket
receivesocket.Listen(2) ''监听socket
Catch ex As Exception
End Try
End Sub
End Class
这例子是我在网上找来后再改了下的,还不能用,你要是做好了,就给我E_Mail一份,谢谢了。 taick@163.com