发现网上关于vbrichclient的教程比较少,但这个实在是好东西,实用性,稳定性都比VB自带的winsock好的多,多客户端不用winsock控件数组。 也不用在各窗体上放winsock,直接在模块中就能实现收发
下面直接上代码,窗体和文本钮、按钮大家自行拖放。要用到VB自带隐藏函数varptr()取内存指针(VbMsdn中没有这个函数,实际上很简单^^)。
VbRichClient5.0.38中包含sqlite3.9支持
上面共享中也包含VbRichClient5.0.38支持库
VbRichClient代替winsock
主要使用
cTCPServer
cTCPClient
cUDP
'---------------------------------------------------------------------
'服务器端,代码最简化,要实现多客户端只要用数组存hsocket就可以
Option Explicit
Dim WithEvents sv As cTCPServer
Dim WithEvents udp1 As cUDP
Dim cHsocket&
Private Sub Form_Load()
Set sv = New cTCPServer
sv.Listen sv.GetHost("127.0.0.1"), 35912
Debug.Print sv.GetHost("")
Set udp1 = New cUDP
udp1.Bind "127.0.0.1", 5616
End Sub
Private Sub sv_DataArrival(ByVal hSocket As Long, ByVal BytesTotal As Long, ByVal FirstBufferAfterOverflow As Boolean)
Dim d() As Byte, s$
ReDim d(BytesTotal - 1)
sv.GetData hSocket, VarPtr(d(0)), BytesTotal '★★关键代码
s = d
Text2.Text = Text2.Text & s & vbCrLf
Debug.Print "收到:" & BytesTotal
End Sub
Private Sub sv_TCPAccepted(ByVal hSocket As Long)
cHsocket = hSocket
Text1.Text = Text1.Text & sv.GetPeerHostIPAndPort(hSocket) & vbCrLf
End Sub
Private Sub sv_TCPDisConnect(ByVal hSocket As Long)
Text3.Text = Text3.Text & sv.GetPeerHostIPAndPort(hSocket) & vbCrLf
End Sub
Private Sub udp1_NewDatagram(ByVal BytesTotal As Long, ByVal FirstBufferAfterOverflow As Boolean)
Dim d() As Byte, s$
ReDim d(BytesTotal - 1)
udp1.GetData VarPtr(d(0)), BytesTotal
s = d
Text2.Text = Text2.Text & s & vbCrLf
End Sub
'-------------------------------------------------------
'客户端
Option Explicit
Dim WithEvents cl As cTCPClient
Dim WithEvents udp1 As cUDP
Dim cid&
Private Sub Command1_Click()
cid = cl.Connect("QgB1", 35912)
End Sub
Private Sub Command2_Click()
cl.Disconnect cid
End Sub
Private Sub Command3_Click()
Dim b() As Byte
b = Text1.Text
cl.SendData cid, VarPtr(b(0)), UBound(b) + 1
End Sub
Private Sub Command4_Click()
Dim d() As Byte, s$
s = "yessss"
d = s
udp1.RemoteIP = "127.0.0.1"
udp1.RemotePort = 5616
u
1