发布网友 发布时间:2022-04-27 04:37
共3个回答
热心网友 时间:2022-06-26 08:08
这个多客户无非就是创建个数组呗。
我直接给代码:
客户端:
Option Explicit
'发送数据
Private Sub command1_Click()
Dim a As String
a = Text2.Text
sock.SendData a
MsgBox ("data sended")
End Sub
Private Sub Form_Load()
Text1.Text = ""
Text2.Text = ""
'远程主机名
sock.RemoteHost = "wenlvzhao.3322.org"
'网络端口
sock.RemotePort = 4981
'发出连接命令
sock.Connect
Command1.Enabled = False
End Sub
'服务器关闭
Private Sub sock_Close()
MsgBox ("socket closed")
End Sub
'连接成功
Private Sub sock_Connect()
MsgBox ("socket connected")
Command1.Enabled = True
End Sub
Private Sub sock_DataArrival(ByVal bytesTotal As Long)
Dim a As String
sock.GetData a
Text1.Text = "[某人]" + a + vbCrLf
End Sub
服务端:
Option Explicit
'定义常量
Const BUSY As Boolean = False
Const FREE As Boolean = True
'定义连接状态
Dim ConnectState() As Boolean
Private Sub Command1_Click()
Text1.Text = Text1.Text & "[无敌闹闹]:" & Text2.Text & vbCrLf
End Sub
Private Sub Form_Load()
ReDim Preserve ConnectState(0 To 1)
On Error Resume Next
ConnectState(0) = FREE
ConnectState(1) = FREE
'指定网络端口号
Listener.LocalPort = "4981"
Text1.Text = ""
Text2.Text = ""
'开始侦听
Listener.Listen
End Sub
Private Sub Listener_ConnectionRequest(ByVal requestID As Long)
Dim SockIndex As Integer
Dim SockNum As Integer
On Error Resume Next
StatusBar1.Panels(1).Text = requestID & "连接请求"
'查找连接的用户数
SockNum = UBound(ConnectState)
If SockNum > 14 Then
Exit Sub
End If
'查找空闲的sock
SockIndex = FindFreeSocket()
'如果已有的sock都忙,而且sock数不超过15个,动态添加sock
If SockIndex > SockNum Then
Load Sock(SockIndex)
End If
ConnectState(SockIndex) = BUSY
Sock(SockIndex).Tag = SockIndex
'接受请求
Sock(SockIndex).Accept (requestID)
End Sub
'客户断开,关闭相应的sock
Private Sub Sock_Close(Index As Integer)
If Sock(Index).State <> sckClosed Then
Sock(Index).Close
End If
ConnectState(Index) = FREE
End Sub
'接收数据
Private Sub Sock_DataArrival(Index As Integer, ByVal bytesTotal As Long)
Dim dx As String
StatusBar1.Panels(1).Text = "数据来自" & Sock(Index).LocalIP
Sock(Index).GetData dx, vbString
Text1.Text = Text1.Text & "[" & Sock(Index).LocalIP & "]" & dx & vbCrLf
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 If
Next i
ReDim Preserve ConnectState(0 To SockCount + 1)
FindFreeSocket = UBound(ConnectState)
End Function
Private Sub Text1_Change()
On Error Resume Next
Dim i As Integer
For i = 1 To Sock.Count - 1
Sock(i).SendData Text1.Text
Next i
End Sub
服务端有两个winsoc控件,一个命名为:Listener,另一个命名为:sock,并且设置index属性为0
窗体设计参照我这个大概就差不多了。
热心网友 时间:2022-06-26 08:09
这个 你要用TCP 还是UDP 如果是UDP的话可以开启多个winsock控件 winsock1 winsock2 等
热心网友 时间:2022-06-26 08:09
Winsock用起来很简单的
服务器只要有本地端口和IP就行了。客户端只要知道服务器端口和IP,然后用Connect方法连接。服务器端收到连接请求后,安排一个空闲的Winsock用Accept方法接受连接请求。