来源:www.cncfan.com | 2006-12-11 | (有13827人读过)
服务器端代码: Option Explicit
Private Sub Command1_Click() If Winsock1.State <> sckClosed Then Winsock1.Close '在当前套接字未关闭时将其关闭 Winsock1.Bind '将设置值生效 Winsock1.Listen '监听端口的连接请求 End Sub
Private Sub Form_Load() Winsock1.LocalPort = Text1.Text End Sub
Private Sub Text3_Change() If Winsock1.State = sckConnected Then Winsock1.SendData Text3.Text '发送到客户端的内容 End Sub
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long) If Winsock1.State <> sckClosed Then Winsock1.Close Winsock1.Accept requestID '在监听的端口有连接请求发生时,立即调用Accept方法,认可连接,使之生效。 End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long) Dim strData As String
Winsock1.GetData strData, vbString '当有数据到达时,调用GetData方法接收之 Text2.Text = strData '将接收的内容更新显示在Text2中 End Sub
客户端代码: Option Explicit
Private Sub Command1_Click() If Winsock1.State <> sckClosed Then Winsock1.Close '如果套接字未关闭,先关闭之 Winsock1.RemoteHost = Text1.Text '确定服务器的主机名 'Winsock1.Bind '绑定套接字属性.不用此句,程序即可执行,用了反而执行不了。 Winsock1.Connect '向服务器发出连接请求 Command1.Enabled = False '使Command1不可用 Command2.Enabled = True '现在可以使其断开
End Sub
Private Sub Command2_Click() Command1.Enabled = True Command2.Enabled = False Winsock1.Close '关闭当前套接字 End Sub
Private Sub Form_Load() Winsock1.RemotePort = "900" End Sub
Private Sub Text3_Change() '实时将Text3的内容反映到服务器的信息框 If Winsock1.State = sckConnected Then Winsock1.SendData Text3.Text End Sub
Private Sub Winsock1_Connect() MsgBox "connected to server!" End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long) Dim str As String
Winsock1.GetData str, vbString '按照字符串类型接收信息 Text2.Text = str '立即更新到Text2中 End Sub
根据原文的代码,稍加改动,在服务器端加了个text3_change(),屏蔽了Winsock1.Connect这一句,程序就完整了.以上代码可复制后,可直接使用,服务器端最好在局域网上的一台电脑运行。 以上代码在win2000、VB6.0下调试通过,可互发信息。
(author/ )
|