socket是网络套接字,使用它我们可以很方便的实现网络的数据传输。在.net中提供了socket类来帮助开
发者调用socket的使用,从而避免了调用socket的动态库来实现socket的麻烦。下面我们就来看一个简单的例子,从这个简单的例子来看看.net中的socket类实现socket是多么的方便。
编程思路:在这个简单的例子中我们将通过socket来实现文件的网络传输和接收功能。要实现这两个功能我们需要通过vs.net建立两个实例来完成。一个发送端,一个接收端。由于文中已经给出了详细的注释这里就不罗嗦了。
发送端
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)'建立终结点 'OpenFileDialog1.ShowDialog() Dim fs As New IO.FileStream("c:\p.doc", 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 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)'监听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) '接收数据并将其保存到一个新的文件中 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 Sub End Class |
通过上面的简单语句我们就完成网络文件的发送和接收,但是这里有一点要注意,此代码只可以接受文本文件和图片文件,对于其他文件的发送和接收将导致编码错误,如果你不相信你可以传输一个mp3文件,再在播放器中打开接收到的mp3文件,你会听到只有开头不到2秒的音乐可以播放。如果想解决这个问题你需要使用,net中的tcp/ip类或udp类来实现,当然调用底层的socket动态库也可以解决这个问题。