Option Explicit
Dim ifConnect As Boolean
'Dim refuse As Boolean 没找到哪里需要使用这个变量了
Private Sub Form_Load()
'Form1.Show '这行可以不要,按你的死循环检测,那就需要
'应该是测试用的,不需要使用
'Winsock2.LocalPort = 30810
'Winsock2.Listen
Winsock1.Protocol = sckTCPProtocol
'Winsock1.LocalPort = 30811 '如果是本地发起连接,不要设置本地端口,如果要设置,也建议设置为0 ,让系统自动选择
Winsock1.Connect "58.215.117.59 ", 30810
'检测状态使用定时器去检测,不要使用循环,这样会造成 CPU 占用率100%。
'Do
'DoEvents
'Loop Until refuse Or ifConnect
'If refuse Then
'Form1.Caption = "强行拒绝"
'Winsock1.Close
'Winsock2.Close
'End If
End Sub
Private Sub Form_Unload(Cancel As Integer)
Winsock1.Close
Winsock2.Close
End Sub
Private Sub Timer1_Timer()
Static js As Long
Const 检测时间 = 10 '每次自动连接间隔时间
If Not ifConnect Then '如果前面没有连接成功,如果已连接成功,则不会再次去连接
Exit Sub
End If
js = js + 1
If js > 检测时间 Then '到了时间
js = 0 '先设置计数器为0
'此段代码是用于确保连接成功但未触发 Winsock1_Connect 事件时的检测,一般情况用不到
If Winsock1.State = sckConnected Then
ifConnect = True
Form1.Caption = "已连接"
Exit Sub
End If
Winsock1.Close '不管状态,先关闭当前连接
DoEvents '确保关闭操作完成
Winsock1.Connect "58.215.117.59 ", 30810 '连接服务器
End If
End Sub
Private Sub Winsock1_Connect()
ifConnect = True
Form1.Caption = "已连接"
End Sub
Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
'可以不用去处理错误信息
' If Number = 10061 Then refuse = True
End Sub