用VB实现客户—服务器(TCP/IP)编程实例

来源:岁月联盟 编辑:zhu 时间:2008-11-25

  现在大多数语言都支持客户-服务器模式编程,其中VB给我们提供了很好的客户-服务器编程方式。下面我们用VB来实现TCP/IP网络编程。

  TCP/IP协议是Internet最重要的协议。VB提供了WinSock控件,用于在TCP/IP的基础上进行网络通信。当两个应用程序使用Socket进行网络通信时,其中一个必须创建Socket服务器侦听,而另一个必须创建Socket客户去连接服务器。这样两个程序就可以进行通信了。

  1.创建服务器,首先创建一个服务端口号。并开始侦听是否有客户请求连接。

  建立一窗体,并向其增加一个Winsock控件(可在工程菜单中的部件项来添加此控件),添加两文本框Text1,Text2,和一按钮Command1。

  Private Sub Form_Load()
    SockServer.LocalPort = 2000 ′服务器端口号,最好大于1000
    SockServer.Listen ′开始侦听
  End Sub
  Private Sub Form_Unload(Cancel As Integer)
    SockServer.Close
  End Sub
  Private Sub SockServer_Close()
    SockServer.Close
  End Sub
  Private Sub SockServer_ConnectionRequest(ByVal requestID As Long)
    SockServer.Close
    SockServer.Accept requestID ′表示客户请求连接的ID号
  End Sub
  ′当客户向服务器发送数据到达后,产生DataArrival事件,在事件中接收数据,GetData方法接收数据。
  Private Sub SockServer_Data
    Arrival(ByVal bytesTotal As Long)
    Dim s As String
    SockServer.GetData s
    Text1.Text = s
  End Sub

  当我需要向客户发送数据时,只需调用SendData方法。

  Private Sub Command1_Click()
    SockServer .SendData Text2.Text
  End Sub

  2.创建客户。要创建客户连接服务器,首先设置服务器主机名,如IP地址、域名或计算机名,然后设置服务器端口,最后连接服务器。

  建立一窗体,并向其增加一个Winsock控件(可在工程菜单中的部件项来添加此控件),取名为:SockC1。添加两文本框Text1,Text2,和一按钮Command1。

  Private Sub Form_Load()
    SockCl.RemoteHost =′127.0.0.1″
    ′表示服务器主机名
    SockCl.RemotePort = 2000
    ′表示服务器端口名
    SockCl.Connect
   ′连接到服务器
End Sub
  Private Sub Form_Unload(Cancel As Integer)
    SockCl.Close
  End Sub
  Private Sub SockCl_Close()
    SockCl.Close
  End Sub
  Private Sub SockCl_DataArrival(ByVal bytesTotal As Long)
    Dim s As String
    SockCl.GetData s ′接收数据到文本框中
    Text1.Text = s
  End Sub
  Private Sub Command1_Click()
    SockCl.SendData Text2.Text ′向服务器发送数据
  End Sub

  3.进行通信。把这两个窗体分别编译成两个EXE文件,服务器Server.exe和客户Client.exe 程序,并把它们分别安装在服务器端和客户端,这样就可以实现两者通信了。