如果系统没有Winsock控件的话,可以下载下面的控件MSWINSCK.OCX,然后将该文件复制到C:WindowsSystem32目录下。
在VBE窗口中,从菜单“工具”->“引用”中,点击“浏览”按钮,选择MSWinSCK.ocx文件,再从“工具箱”的“附加控件”中选择Microsoft Winsock Control。
此时使用Winsock控件的话,将会出现提示不安全的ActiveX控件的提示。可以点击同时下载的REG文件注册该控件即可。
一般在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)
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