Option Explicit
'Structure to store information about a chat client.
Private Type CHAT_CLIENT
strUsername As String
strIP As String
'Other info...
End Type
'Variable to store all chat client's info.
Private udtClient() As CHAT_CLIENT
'Maximum number of clients that can connect.
'Change to whatever you want.
Private Const MAX_CLIENTS As Integer = 32767
'Simple function to return the UBound of udtClient array without an error.
Private Function UBClient() As Long
On Error GoTo ErrorHandler
UBClient = UBound(udtClient())
Exit Function
ErrorHandler:
Exit Function
End Function
'Finds the next available socket to use to accept the connection on.
Private Function NextSocket() As Integer
Dim intLoop As Integer, intFound As Integer
'First check if we even have any other winsock controls loaded.
'If not, then just load #1.
If sckServer.ubound = 0 Then
'Load next socket.
Load sckServer(1)
sckServer(1).Close
NextSocket = 1
Else
'There are other winsock controls loaded.
'Loop through all of them.
'If one of them isn't being used (State = sckClosed) then we can use that one.
'If we can't find one already loaded then we need to load a new one
'unless we've already reached MAX_CLIENTS.
For intLoop = 1 To sckServer.ubound
If sckServer(intLoop).State = sckClosed Then
intFound = intLoop 'Found one.
Exit For
End If
Next intLoop
If intFound > 0 Then 'Check if we found one already loaded.
NextSocket = intFound
Else
'Didn't find one. Check if we can load a new one.
If sckServer.ubound < MAX_CLIENTS Then
intFound = sckServer.ubound + 1
Load sckServer(intFound)
sckServer(intFound).Close
NextSocket = intFound
Else
'We reached MAX_CLIENTS.
Debug.Print "CONNECTION REFUSED: MAX_CLIENTS REACHED"
End If
End If
End If
End Function
Private Sub sckServer_Close(Index As Integer)
'A client has disconnected.
'To acccess this client's info we can just use the Index property of the winsock.
Debug.Print udtClient(Index).strIP & " disconnected."
End Sub
Private Sub sckServer_ConnectionRequest(Index As Integer, ByVal requestID As Long)
'Find the next available socket to use.
Dim intNext As Integer
intNext = NextSocket
If intNext > 0 Then 'Found one.
sckServer(intNext).Accept requestID 'Accept connection.
'Now associate a client in udtClient() with this winsock control.
'We may need to ReDim the array in case this one hasn't been loaded yet.
If intNext > UBClient() Then
ReDim Preserve udtClient(0 To intNext) As CHAT_CLIENT
End If
With udtClient(intNext)
.strUsername = ""
.strIP = sckServer(intNext).RemoteHostIP
End With
End If
End Sub