vb中利用winsock控件,tcp協(xié)議實(shí)現(xiàn)多客戶端連接
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
通信程序通常都是采用Client/Server形式。這就要求作為服務(wù)器的主機(jī)可以同時(shí)處理多個(gè)客戶的請(qǐng)求。因此在編寫服務(wù)器程序時(shí)要添加多個(gè)Winsock控件。在開(kāi)始我們先加入兩個(gè)Winsock控件。其中一個(gè)用來(lái)偵聽(tīng)網(wǎng)上請(qǐng)求信號(hào),取名為L(zhǎng)istener;另外一個(gè)為初始的連接口,取名叫Sock(0)。注意,后一個(gè)控件要設(shè)為動(dòng)態(tài)數(shù)組的形式,以后當(dāng)客戶增多時(shí),可在這個(gè)控件基礎(chǔ)上動(dòng)態(tài)增加。由于受資源限制,我們?cè)诒纠性O(shè)定最多可以同時(shí)接納15個(gè)客戶??蛻魴C(jī)一般只與一個(gè)主機(jī)相連,因此程序只須一個(gè)Winsock進(jìn)行連接就足夠了。這個(gè)程序要用到的控件較少,除了Winsock和Form控件外,只須再添加Commmand控件即可。下面是具體程序和詳細(xì)注釋。 ****************************** 服務(wù)器程序 ****************************** Option Explicit 定義常量 Const BUSY As Boolean = False Const FREE As Boolean = True 定義連接狀態(tài) Dim ConnectState() As Boolean Private Sub Form_Load() ReDim Preserve ConnectState(0 To 1) On Error Resume Next ConnectState(0) = FREE ConnectState(1) = FREE ’指定網(wǎng)絡(luò)端口號(hào) Listener.LocalPort = 1011 ‘開(kāi)始偵聽(tīng) Listener.Listen End Sub Private Sub Listener_ConnectionRequest(ByVal requestID As Long) Dim SockIndex As Integer Dim SockNum As Integer On Error Resume Next Form1.Print requestID & "連接請(qǐng)求" 查找連接的用戶數(shù) SockNum = UBound(ConnectState) If SockNum > 14 Then Form1.Print SockIndex & "" Exit Sub End If 查找空閑的sock SockIndex = FindFreeSocket() ’如果已有的sock都忙,而且sock數(shù)不超過(guò)15個(gè),動(dòng)態(tài)添加sock If SockIndex > SockNum Then Load Sock(SockIndex) End If ConnectState(SockIndex) = BUSY Sock(SockIndex).Tag = SockIndex 接受請(qǐng)求 Sock(SockIndex).Accept (requestID) Form1.Print SockIndex & "接受請(qǐng)求" End Sub 客戶斷開(kāi),關(guān)閉相應(yīng)的sock Private Sub Sock_Close(Index As Integer) If Sock(Index).State <> sckClosed Then Sock(Index).Close End If ConnectState(Index) = FREE Form1.Print Index & "close" End Sub 接收數(shù)據(jù) Private Sub Sock_DataArrival(Index As Integer, ByVal bytesTotal As Long) Dim dx As Double Form1.Print "數(shù)據(jù)來(lái)自" & Index Sock(Index).GetData dx, vbDouble Form1.Print "dx=" & dx End Sub 尋找空閑的sock Public Function FindFreeSocket() Dim SockCount, i As Integer SockCount = UBound(ConnectState) For i = 0 To SockCount If ConnectState(i) = FREE Then FindFreeSocket = i Exit Function End Ifs Next i ReDim Preserve ConnectState(0 To SockCount + 1) FindFreeSocket = UBound(ConnectState) End Function *************************** 客戶程序 ’*************************** Option Explicit 發(fā)送數(shù)據(jù) Private Sub command1_Click() Dim dx As Double dx = 23.9 sock.SendData dx MsgBox ("data sended") End Sub Private Sub Form_Load() 遠(yuǎn)程主機(jī)名 sock.RemoteHost = "media2" 網(wǎng)絡(luò)端口 sock.RemotePort = 1011 發(fā)出連接命令 sock.Connect Command1.Enabled = False End Sub 服務(wù)器關(guān)閉 Private Sub sock_Close() MsgBox ("socket closed") End Sub 連接成功 Private Sub sock_Connect() MsgBox ("socket connected") Command1.Enabled = True End Sub 該文章在 2013/12/10 22:12:03 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |