The DSAPI libray provides a robust HTTPListener component designed to facilitate rapid development of both HTTP servers and clients. This component serves as a lightweight alternative to traditional web servers like IIS, allowing developers to handle network traffic and custom requests efficiently.
Configuring the HTTP Server
To initialize the server, instantiate the DSAPI.Network.HTTPListener class. Utilizing the WithEvents keyword allows for seamless integration of event-driven logic.
' Initialize the listener
Private WithEvents AppServer As New DSAPI.Network.HTTPListener
Sub SetupServer()
With AppServer
.Port = 8080
.UsePrefix = True
.PrefixString = "api/v1"
.AllowExternalAccess = True
.Start()
End With
End Sub
Configuration Parameters:
- Port: Defines the network port for the listener.
- UsePrefix/PrefixString: Acts as a security mechanism. Requests must include the specified prefix in the URL path (e.g.,
http://localhost:8080/api/v1). If enabled, any request lacking this path structure is rejected. - AllowExternalAccess: Determines whether the server accepts connections from outside the local machine.
Handling Server Events
The component exposes several events to manage the lifecycle and security of the connection:
Private Sub AppServer_OnRequest(client As DSAPI.Network.HTTPListener.ClientContext) Handles AppServer.OnRequest
' Handle legitimate client incoming data
Dim reader As New IO.StreamReader(client.InputStream)
Dim payload As String = reader.ReadToEnd()
Select Case payload
Case "status"
AppServer.SendResponse(client, "System Online")
Case "fetch_data"
AppServer.SendResponse(client, IO.File.ReadAllBytes("C:\data.bin"))
Case Else
AppServer.SendResponse(client, "Invalid Command")
End Select
End Sub
Private Sub AppServer_OnError(ex As Exception) Handles AppServer.OnError
' Log or handle server exceptions
End Sub
Implementing an HTTP Client
Communication can be established using standard .NET framwork networking classes. The following example demonstrates sending a POST request containing custom data to the DSAPI listener.
Public Function SendRequest(endpoint As String, port As Integer, path As String, message As String) As String
Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create($"{endpoint}:{port}/{path}")
Dim buffer() As Byte = System.Text.Encoding.UTF8.GetBytes(message)
request.Method = "POST"
request.ContentLength = buffer.Length
Using stream = request.GetRequestStream()
stream.Write(buffer, 0, buffer.Length)
End Using
Using response = request.GetResponse()
Using reader As New IO.StreamReader(response.GetResponseStream())
Return reader.ReadToEnd()
End Using
End Using
End Function
This implementation ensures that the payload is sent via request stream rather than exposed in the URL query string, maintaining a cleaner and more secure communication interface.