The previous article explored DSAPI's versatile HTTP server and client components. This guide introduces an optimized, high-performance solution for HTTP-based communication that dramatically simplifies both server and client implementation.
This command-oriented version delivers an unprecedentedly simple approach to HTTP monitoring services. Unlike previous implementations, this version integrates both server and client capabilities within a single component, streamlining development significantly.
Setting Up a Command-Based HTTP Server
The implementation requires only a handful of lines:
Private WithEvents CommandServer As New DSAPI.Network.HttpListener_CommandVersion
With CommandServer
.BoundPort = 2000
.UseParameterPrefix = True
.AllowExternalConnections = True
.StartListening()
End With
This compact setup establishes a fully functional HTTP command server. The following events are available for handling various states:
Private Sub CommandServer_ServerStarted() Handles CommandServer.ListeningStarted
' Server initialization complete
End Sub
Private Sub CommandServer_ServerStopped() Handles CommandServer.ListeningStopped
' Server shutdown complete
End Sub
Private Sub CommandServer_CommandReceived(Client As DSAPI.Network.HttpListener_CommandVersion.CommandClient, CommandText As String) Handles CommandServer.CommandReceived
' Process incoming commands
End Sub
Private Sub CommandServer_ErrorOccurred(Error As Exception) Handles CommandServer.ErrorEncountered
' Handle errors gracefully
End Sub
Processing Incoming Commands
The received command arrives directly as a string parameter, enabling straightforward conditional logic:
Private Sub CommandServer_CommandReceived(Client As DSAPI.Network.HttpListener_CommandVersion.CommandClient, CommandText As String) Handles CommandServer.CommandReceived
Select Case CommandText
Case "greet"
CommandServer.WriteToClient(Client, "Hello, there!")
Case "download"
CommandServer.WriteToClient(Client, IO.File.ReadAllBytes("c:\sample.rar"))
Case Else
CommandServer.WriteToClient(Client, "Unknown command")
End Select
End Sub
The command content arrives ready for immediate processing. Response data can be either text or binary payloads such as file contents, providing flexibility for various use cases.
Creating a Command-Based HTTP Client
Client implementation proves equally straightforward:
Private WithEvents RequestClient As New DSAPI.Network.HttpListener_CommandVersion.CommandClient
With RequestClient
.Timeout = 1000
.ServerAddress = "127.0.0.1"
.ServerPort = 2000
End With
Sending Commands and Receiving Responses
Interacting with the server requires just a single line:
MessageBox.Show(RequestClient.GetData("greet"))
That's genuinely all that's required. The command-oriented approach eliminates complexity while maintaining full functionality, making it ideal for scenarios requiring rapid development and clean, maintainable code.