httpListener class in Vulcan.NET/X#

Mar 05
2016

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:
// http://mikehadlow.blogspot.it/2006/07/playing-with-httpsys.html
//
// 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
#using VulcanHttpListener.riedmann.it

begin namespace VulcanHttpListener.riedmann.it

function Start() as void
 local oProgram as MainProgram

 oProgram := MainProgram{}
 oProgram:Start()

 return

class MainProgram
 protect _oListener as HttpListener

 constructor()

  _oListener := HttpListener{}

 return

 method Start() as void

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

 return

 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] )
  next
  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 )

  return

end class

end namespace