在VBA中调⽤winsock控件
如果系统没有Winsock控件的话,可以下载下⾯的控件MSWINSCK.OCX,然后将该⽂件复制到C:\Windows\System32⽬录下。
在VBE窗⼝中,从菜单“⼯具”->“引⽤”中,点击“浏览”按钮,选择⽂件,再从“⼯具箱”的“附加控件”中选择Microsoft Winsock Control。
此时使⽤Winsock控件的话,将会出现提⽰不安全的ActiveX控件的提⽰。可以点击同时下载的REG⽂件注册该控件即可。
(48.41 KB, 下载次数: 495)
⼀般在Excel的窗体中添加Winsock控件。
使⽤Winsock控件的应⽤程序⼀般是Client/Server结构,也就是客户端/服务器端。
以服务端为例,⼀般的步骤是:
先设置LocalPort本地端⼝,然后使⽤Listen⽅法侦听数据请求。然后处理ConnectionRequest和DataArrival事件。使⽤完后使⽤Close⽅法关闭连接。
Private Sub UserForm_Initialize()
Winsock1.LocalPort = 1999
Winsock1.Listen
End Sub
Private Sub UserForm_Terminate()
Winsock1.Close
End Sub
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
If Winsock1.State <> sckClosed Then Winsock1.Close
Winsock1.Accept requestID
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim Buffer() As Byte
TransferedBytes = TransferedBytes + bytesTotal
ReDim Buffer(bytesTotal - 1)
Winsock1.GetData Buffer, vbArray + vbByte
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)activex 控件
Debug.Print "Sock Err:" & Description
End Sub
⽽客户端的⼀般步骤如下:
设置远程服务器端⼝RemotePort属性,然后使⽤Connect⽅法连接。处理ConnectionRequest和DataArrival事件。发送数据就直接使⽤Send⽅法就可以了,可以发送字符串或者Byte数组。
Private Sub UserForm_Initialize()
Winsock1.RemoteHost = "127.0.0.1"
Winsock1.RemotePort = 2999
Winsock1.Connect
End Sub
Private Sub UserForm_Terminate()
Winsock1.Close
End Sub
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
If Winsock1.State <> sckClosed Then Winsock1.Close
Winsock1.Accept requestID
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
Winsock1.GetData strData, vbString
If strData = "OK" Then
Winsock1.Close
Winsock1.RemotePort = 1999
Winsock1.Connect
MsgBox "You can send file now"
End If
End Sub
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论