我用winsock编制了一个类似于服务器和客户端的通信对话程序,分别用两个窗体,服务器和客户端完成:
服务器:里面有一个按钮控件command1"退出服务器",两个text文本,名称为:textsend和textget,一个winsock
控件,名称为:winsockserver,下面是它们的代码:
Private Sub Command1_Click()
Winsockserver.Close
End
End Sub
Private Sub Form_Load()
Textsend.Visible = False
Textget.Visible = False
Winsockserver.LocalPort = 12315
Winsockserver.Listen
End Sub
Private Sub Textsend_Change()
Winsockserver.SendData Textsend.Text
End Sub
Private Sub Winsockserver_Close()
Winsockserver.Close
Form_Load
End Sub
Private Sub Winsockserver_ConnectionRequest(ByVal requestID As Long)
Textsend.Visible = True
Textget.Visible = True
If Winsockserver.State <> sckClosed Then
Winsockserver.Close
Winsockserver.Accept requestID
End If
End Sub
Private Sub Winsockserver_DataArrival(ByVal bytesTotal As Long)
Dim tmpstr As String
Winsockserver.GetData tmpstr
Textget.Text = tmpstr
End Sub
客户端:里面有两个按钮控件command1"退出客户端"和command2"连接主机", 一个用于显示主机名称的
text文档connecthost,两个类似于上述服务器的发送和接收的text文档textsend和textget,一个winsock
控件,名称为 winsockclient,它们的代码为:
Private Sub Command1_Click()
Winsockclient.Close
End
End Sub
Private Sub Command2_Click()
Winsockclient.RemoteHost = connecthost.Text
Winsockclient.Connect
End Sub
Private Sub Form_Load()
textsend.Visible = False
Textget.Visible = False
Winsockclient.RemotePort = 12315
Winsockclient.RemoteHost = "localhost"
End Sub
Private Sub textsend_Change()
Winsockclient.SendData textsend.Text
End Sub
Private Sub Winsockclient_Connect()
textsend.Visible = True
Textget.Visible = True
Command2.Visible = False
End Sub
Private Sub Winsockclient_DataArrival(ByVal bytesTotal As Long)
Dim tmpstr As String
Winsockclient.GetData tmpstr
Textget.Text = tmpstr
Textget.Refresh
End Sub
我在同一台电脑上执行了一下,虽然连接成功,两边也可以互发数据,但不知道为什么当我把发送端的文字去掉后,接收端却残留一些文字未能去清,你们也可以试一下,高手们,能帮我解决一下吗?
[此贴子已经被作者于2007-4-14 21:16:17编辑过]