明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學習分享的學習平臺!

用.net中的socket完成文件傳輸

[摘要]socket是網(wǎng)絡套接字,使用它我們可以很方便的實現(xiàn)網(wǎng)絡的數(shù)據(jù)傳輸。在.net中提供了socket類來幫助開發(fā)者調(diào)用socket的使用,從而避免了調(diào)用socket的動態(tài)庫來實現(xiàn)socket的麻煩。下面我們就來看一個簡單的例子,從這個簡單的例子來看看.net中的socket類實現(xiàn)socket是多么的...
socket是網(wǎng)絡套接字,使用它我們可以很方便的實現(xiàn)網(wǎng)絡的數(shù)據(jù)傳輸。在.net中提供了socket類來幫助開

發(fā)者調(diào)用socket的使用,從而避免了調(diào)用socket的動態(tài)庫來實現(xiàn)socket的麻煩。下面我們就來看一個簡單的例子,從這個簡單的例子來看看.net中的socket類實現(xiàn)socket是多么的方便。

  編程思路:在這個簡單的例子中我們將通過socket來實現(xiàn)文件的網(wǎng)絡傳輸和接收功能。要實現(xiàn)這兩個功能我們需要通過vs.net建立兩個實例來完成。一個發(fā)送端,一個接收端。由于文中已經(jīng)給出了詳細的注釋這里就不羅嗦了。


  發(fā)送端


Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object,
  ByVal e As System.EventArgs) Handles Button1.Click
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.0.1"), 8888)'建立終結(jié)點
'OpenFileDialog1.ShowDialog()
Dim fs As New IO.FileStream("c:\p.doc",
  IO.FileMode.OpenOrCreate, IO.FileAccess.Read)'要傳輸?shù)奈募?br> Dim fssize(fs.Length - 1) As Byte
Dim strread As New IO.BinaryReader(fs)'流處理要傳輸?shù)奈募?br> 'fs.Read(fssize, 0, fssize.Length - 1)
strread.Read(fssize, 0, fssize.Length - 1)
sendsocket.Connect(ipendpiont)'連接遠程計算機
sendsocket.Send(fssize)'發(fā)送文件
Label1.Text = fs.Length()
fs.Close()
sendsocket.Shutdown(Net.Sockets.SocketShutdown.Send)
  '關閉發(fā)送連接
sendsocket.Close()'關閉本機socket
End Sub
End Class

  接收端

Public Class Form1
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 Form1_Load(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles MyBase.Load
Dim hostipendpiont As New Net.IPEndPoint
  (Net.IPAddress.Parse("192.168.0.1"), 8888)
receivesocket.Bind(hostipendpiont)
  '建立遠程計算機的的socket
receivesocket.Listen(2)'監(jiān)聽socket
End Sub

Private Sub Button1_Click(ByVal sender As Object,
  ByVal e As System.EventArgs) Handles Button1.Click
Dim recfs As New IO.FileStream("p.doc",
  IO.FileMode.OpenOrCreate)
  '接收數(shù)據(jù)并將其保存到一個新的文件中
Dim recbyte(229888) As Byte
Dim hostsocket As Net.Sockets.Socket =
  receivesocket.Accept()
  '同意和發(fā)送端計算機建立連接
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 Sub
End Class

  通過上面的簡單語句我們就完成網(wǎng)絡文件的發(fā)送和接收,但是這里有一點要注意,此代碼只可以接受文本文件和圖片文件,對于其他文件的發(fā)送和接收將導致編碼錯誤,如果你不相信你可以傳輸一個mp3文件,再在播放器中打開接收到的mp3文件,你會聽到只有開頭不到2秒的音樂可以播放。如果想解決這個問題你需要使用,net中的tcp/ip類或udp類來實現(xiàn),當然調(diào)用底層的socket動態(tài)庫也可以解決這