远程控制服务端:
Option Explicit
Function WinSockInitial(ByVal WinSock As WinSock, ByVal IntPort As Long) As Boolean
On Error GoTo InitialError
'验证winsock控件初始化连接的端口号)
If 0 <= IntPort And IntPort <= 65535 Then
If IntPort Mod 1 = 0 Then
WinSock.LocalPort = IntPort
WinSockInitial = True
Exit Function
Else
MsgBox "端口配置应为整数", vbOKOnly + vbExclamation, "错误提示"
Exit Function
End If
ElseIf IntPort < 0 Then
MsgBox "端口配置为非负数", vbOKOnly + vbExclamation, "错误提示"
Exit Function
ElseIf IntPort > 65535 Then
MsgBox "端口配置超出最大值65535", vbOKOnly + vbExclamation, "错误提示"
Exit Function
End If
InitialError:
WinSockInitial = False
MsgBox "Unexpected error" & _
Str$(Err.Number) & _
" in subroutine WinSockInitial" & _
vbCrLf & _
Err.Description
Exit Function
End Function
Private Sub Form_Load()
' '服务器端Winsock控件的初始化
If WinSockInitial(tcpServer, 5000) = False Then
Unload Me
Exit Sub
Else
tcpServer.Listen
Debug.Print tcpServer.State
frmClient.Show
End If
End Sub
Private Sub tcpServer_ConnectionRequest(ByVal requestID As Long)
'接受请求
If tcpServer.State <> sckClosed Then tcpServer.Close
tcpServer.Accept requestID
End Sub
Private Sub tcpServer_DataArrival(ByVal bytesTotal As Long)
Dim strData As String '声明一个变量,盛放数据
tcpServer.GetData strData, vbString '调用GetData方法
txtOutPut.Text = txtOutPut.Text + strData '将数据传送到txtOutPut文本框
End Sub
Private Sub txtSendData_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyReturn Then
tcpServer.SendData txtSendData.Text
End If
End Sub
客户端:
Option Explicit
Private Sub Form_Load()
tcpClient.RemoteHost = "192.168.24.156"
tcpClient.RemotePort = 5000
tcpClient.Connect '调用Connect方法初始化连接
End Sub
Private Sub Form_Unload(Cancel As Integer)
tcpClient.Close '关闭连接
End Sub
Private Sub tcpClient_DataArrival(ByVal bytesTotal As Long)
Dim strData As String '声明变量盛放数据
If tcpClient.State = 7 Then
tcpClient.GetData strData '调用GetData方法传送数据
txtOutPut.Text = strData '将数据放到TxtOutPut文本框显示
End If
End Sub
Private Sub txtSend_KeyDown(KeyCode As Integer, Shift As Integer)
'按回车发送数据
If KeyCode = vbKeyReturn Then
tcpClient.SendData txtSend.Text '当文本框数据发生变换时,通过tcpClient控件调用SendData方法发送数据
End If
End Sub
同时控制多台客户端的服务端:
Option Explicit
Private intMax As Long
Private Sub Form_Load()
intMax = 0 '初始化intMax变量
sckServer(0).LocalPort = 5000
sckServer(0).Listen
End Sub
Private Sub sckServer_ConnectionRequest(Index As Integer, ByVal requestID As Long)
If Index = 0 Then
intMax = intMax + 1
Load sckServer(intMax)
sckServer(intMax).LocalPort = 0
sckServer(intMax).Accept requestID
Load txtData(intMax)
End If
End Sub