httpListener class in Vulcan.NET/X#

Mar 05

This is code for a Vulcan.NET or X# Listener class (ported over from C#):

// Application : HttpListener
// httpListener.prg , Created : 16.02.2016 08:37
// User : Wolfgang
// C# code see here:
// to make it run without admin rights you need something like this one:
// netsh http add urlacl url="http://*:8080/" user=[username] listen=yes

#using System
#using System.Net
#using System.Text
#using System.IO

begin namespace

function Start() as void
 local oProgram as MainProgram

 oProgram := MainProgram{}


class MainProgram
 protect _oListener as HttpListener


  _oListener := HttpListener{}


 method Start() as void

  _oListener:Prefixes:Add( "http://*:8080/" )
  Console.WriteLine( "Listening on port 8080, hit enter to stop" )
  _oListener:BeginGetContext( AsyncCallback{ self:GetContextCallback }, null )


 method GetContextCallback( oResult as IAsyncResult ) as void
  local oContext as HttpListenerContext
  local oRequest as HttpListenerRequest
  local oResponse as HttpListenerResponse
  local oSB as StringBuilder
  local oString as string
  local oBuffer as byte[]
  local oOutput as Stream

  oContext := _oListener:EndGetContext( oResult )
  oRequest := oContext:Request
  oResponse := oContext:Response

  oSB := StringBuilder{}
  oSB:Append( e"\n" )
  oSB:AppendFormat( e"HttpMethod: {0}\n", oRequest:HttpMethod )
  oSB:AppendFormat( e"URI: {0}\n", oRequest:Url:AbsoluteUri )
  oSB:AppendFormat( e"Local path: {0}\n", oRequest:Url:LocalPath )
  oSB:Append( e"\n" )
  foreach cKey as string in oRequest:QueryString:Keys
   oSB:AppendFormat( e"Query: {0} = {1}\n", cKey, oRequest:QueryString[cKey] )
  oSB:Append( e"\n" )

  oString := oSB:ToString()
  oBuffer := System.Text.Encoding.UTF8:GetBytes( oString )
  oResponse:ContentLength64 := oBuffer:Length
  oOutput := oResponse:OutputStream
  oOutput:Write( oBuffer, 0, oBuffer:Length )

  _oListener:BeginGetContext( AsyncCallback{ self, @GetContextCallback() }, null )


end class

end namespace