2019年5月17日 星期五

[C#] HTTP host service in windows desktop app

We need to create HTTP host service in a windows desktop app to receive HTTP POST request. (Only one request will be handled at the same time.)

Use HttpListener and add necessary prefixes and start it


HttpListener server = new HttpListener();
string url = $"http://localhost:{port}/";
server.Prefixes.Add(url);

url = $"http://127.0.0.1:{port}/";
server.Prefixes.Add(url);

IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
url = $"http://{ipHostInfo.AddressList[0].ToString()}:{port}/";
server.Prefixes.Add(url);

server.Start();
logger.Info($"Listening to [{url}]...");
Use loop process each HTTP request

while( true )
{
  if( isStopping )
     break;
  HttpListenerContext context = server.GetContext();
  HttpListenerResponse response = context.Response;
  ...
}
Retrieve API path to determine which command is called

StringBuilder builder;
switch( context.Request.Url.LocalPath )
{
    case "/api/command1":
        builder = new StringBuilder("OK");
        break;
    default:
        builder = new StringBuilder("Unrecognized API");
        failureFlag = true;
        break;
}
Retrieve Body and convert it into JSON Object

try
{
    using( var reader = new StreamReader(context.Request.InputStream,
                                         context.Request.ContentEncoding) )
    {
        bodyText = reader.ReadToEnd();
        logger.Info($"HTTP POST body\n{bodyText}");

        var boardMsg = jsonSerializationUtil.DeserializeFromString(bodyText);
        if( boardMsg == null )
            builder = new StringBuilder("JSON format deserialization failure.");
        else
        {
           // Process boardMsg...
        }
    }
}
catch( Exception ex )
{
    logger.Warn(ex);
    builder = new StringBuilder("Body loading failure.");
}
Convert response string into bytes and send it back

string something = builder.ToString();
byte[] buffer = Encoding.UTF8.GetBytes(something);
response.ContentLength64 = buffer.Length;
System.IO.Stream st = response.OutputStream;
st.Write(buffer, 0, buffer.Length);

context.Response.Close();

沒有留言:

搜尋此網誌