接收端 Public Class Form1 Inherits System.Windows.Forms.Form Dim listener As New System.Net.Sockets.Socket (Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp) '初始socket Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load '指定ip和端口 Dim ipHostInfo As System.Net.IPHostEntry = System.Net.Dns.Resolve(System.Net.Dns.GetHostName()) Dim ipAddress As System.Net.IPAddress = ipHostInfo.AddressList(0) Dim localEndPoint As New System.Net.IPEndPoint(ipAddress, 11000) listener.Bind(localEndPoint) listener.Listen(10) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim bytes() As Byte = New [Byte](1024) {} Dim handler As System.Net.Sockets.Socket = listener.Accept()'建立连接请求 Dim data As String = Nothing bytes = New Byte(1024) {} Dim bytesRec As Integer = handler.Receive(bytes)'接收数据 data += System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec) TextBox1.Text = data Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data) handler.Shutdown(Net.Sockets.SocketShutdown.Both) handler.Close() End Sub End Class |
说明:本程序未进行异常处理,所以不可以连续点"接收"键,其原因是让读者快速掌握.net中的socket编程基础(如要进行异常处理,请加入try块,详情见msdn)。由于本代码的中数据编码使用的是英文编码,所以不支持中文字体(通过对编码的修改可以发送中文,见msdn)。本文的目的不是教各位编写聊天程序,所以在看本文时请从socket方面进行思考。本程序在局域网和internet中测试时都通过了,如果是想在internet中使用本程序,需要将文中的接收和发送方的Dim ipe As New System.Net.IPEndPoint(ipAddress, 11000)语句中的ipaddress修改为真的ip地址并分别将发送和接收安装于不同ip地址的计算机上。
本程序开发环境vb.net,os是windows 2000。不过在微软最新的vs.net2003中也可以编写和编译本程序。
|