我尝试使用下面的代码来处理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.State“连接”到Winsock1_Connect子程序。 我想使用标准的MS库,因为我没有在我的电脑上的管理权限,我不能够注册一些自定义库。 谁能告诉我,我哪里错了?
您是否使用MSWinsock卡住?
下面是使用自定义的Winsock对象的位置/教程。
还...你需要一个“类”模块中声明为Winsock1 WITHEVENTS:
Private WithEvents Winsock1 As Winsock
最后,请确保您引用winsock的ocx控件。
工具 - >引用 - >浏览 - >%SYSEM%\ MSWINSCK.OCX
文档关于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
...