Close Socket


Description:
This bit of code demonstrates implementing a simple web server. The primary reason to use API's to send data here is so we can shutdown the socket before closing it. This way data that's queued up in the socket is guaranteed to be sent before the socket is closed.
 
Code:
Private Const SD_BOTH = 2

Private Declare Function shutdown Lib "wsock32" (ByVal hSocket As Long, _
   ByVal nHow As Long) As Long
   
Private Declare Function closesocket Lib "wsock32" (ByVal hSocket _
   As Long) As Long
   
Private Declare Function send Lib "wsock32" (ByVal hSocket As Long, _
   ByVal szOutbound As String, ByVal cchOutbound As Long, _
   ByVal nOther As Long) As Long

Private Sub sckIn_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    
    Dim sOutBound As String
    Dim hSocket As Long
    Dim cCharSent As Long
    
    sOutBound = "HTTP 1/1 OK" & vbNewLine & _
                "Content-Type: text/html" & vbNewLine & _
                vbNewLine & _
                "<html><body>Hello World!</body></html>" & vbNewLine
                
    hSocket = sckIn(Index).SocketHandle
    
    Do While sOutBound <> ""
    
        cCharSent = send(hSocket, sOutBound, Len(sOutBound), 0)
        
        If cCharSent >= Len(sOutBound) Then
            sOutBound = ""
        Else
            sOutBound = Mid(sOutBound, cCharSent + 1)
        End If
        
    Loop
    
    shutdown hSocket, SD_BOTH
    sckIn(Index).Close
    
    Unload sckIn(Index)

End Sub
 
Sample Usage:
 
n/a