我正在尝试使用以下代码处理Winsock_Connect事件(实际上我需要在Excel宏中使用它):
Dim Winsock1 As Winsock 'Object type definition
Sub Init()
Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization
Winsock1.RemoteHost = "MyHost"
Winsock1.RemotePort = "22"
Winsock1.Connect
Do While (Winsock1.State <> sckConnected)
Sleep 200
Loop
End Sub
'Callback handler
Private Sub Winsock1_Connect()
MsgBox "Winsock1::Connect"
End Sub
但它永远不会进入Winsock1_Connect子程序,尽管Winsock1.State是“已连接”。 我想使用标准MS库,因为我的PC上没有管理权限,我无法注册一些自定义库。 任何人都可以告诉我,我错了吗?
答案 0 :(得分:3)
你是否坚持使用MSWinsock?
Here是使用自定义winsock对象的网站/教程。
另外......你需要在“Class”模块中声明Winsock1 WithEvents :
Private WithEvents Winsock1 As Winsock
最后,请确保引用winsock ocx控件 工具 - &gt;参考文献 - &gt;浏览 - &gt; %SYSEM%\ MSWINSCK.OCX
答案 1 :(得分:0)
有关 Winsock控制的文档:
http://msdn.microsoft.com/en-us/library/aa228119%28v=vs.60%29.aspx
这里的例子:
http://support.microsoft.com/kb/163999/en-us
我在VBscript中使用事件处理的简短示例:
Dim sock
Set sock = WScript.CreateObject("MSWinsock.Winsock","sock_")
sock.RemoteHost = "www.yandex.com"
sock.RemotePort = "80"
sock.Connect
Dim received
received = 0
Sub sock_Connect()
WScript.Echo "[sock] Connection Successful!"
sock.SendData "GET / HTTP/1.1"& vbCrLf & "Host: " & sock.RemoteHost & vbCrLf & vbCrLf
End Sub
Sub sock_Close()
WScript.Echo "[sock] Connection closed!"
End Sub
Sub sock_DataArrival(Byval b)
Dim data
sock.GetData data, vbString
received = received + b
WScript.Echo "---------------------------------------"
WScript.Echo " Bytes received: " & b & " ( Total: " & received & " )"
WScript.Echo "---------------------------------------"
WScript.Echo data
End Sub
'Wait for server close connection
Do While sock.State <> 8
rem WScript.Echo sock.State
WScript.Sleep 1000
Loop
输出将是:
cscript /nologo sockhttp.vbs
[sock] Connection Successful!
-------------------------------
Bytes received: 1376 ( Total: 1376 )
-------------------------------
HTTP/1.1 200 Ok
Date: Mon, 08 Dec 2014 15:41:36 GMT
Content-Type: text/html; charset=UTF-8
Cache-Control: no-cache,no-store,max-age=0,must-revalidate
Expires: Mon, 08 Dec 2014 15:41:36 GMT
...