伝説のどいつまの伝説~失敗編~

岩美に永住したい新米エンジニアのあれやこれやな話。

【C#】HttpListenerで簡易サーバを作ってみよう。

この度転職いたしまして、Webの知識諸々必要になったので目下勉強中です。

今はReal World HTTPをベースに、
必要な言語がC#なので、Go->C#に書き換えながらやってます。

Real World HTTP ―歴史とコードに学ぶインターネットとウェブ技術

Real World HTTP ―歴史とコードに学ぶインターネットとウェブ技術

まずは、簡易サーバにアクセスしたらHTMLを返すというようなものを復習として作成しましたので投下。

using System;
using System.Diagnostics;
using System.Net;
using System.Text;

namespace D01tsumaTask1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // HTTPリスナー作成
                HttpListener listener = new HttpListener();

                // リスナー設定
                listener.Prefixes.Clear();
                listener.Prefixes.Add(@"http://+:8080/");

                // リスナー開始
                listener.Start();

                while (true)
                {
                    // リクエスト取得
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;

                    // レスポンス取得
                    HttpListenerResponse response = context.Response;

                    // HTMLを表示する
                    if (request != null)
                    {
                        byte[] text = Encoding.UTF8.GetBytes("<html><head><meta charset='utf-8'/></head><body><h1>どいつま.com</h1></body></html>");
                        response.OutputStream.Write(text, 0, text.Length);
                    }
                    else
                    {
                        response.StatusCode = 404;
                    }
                    response.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

先輩より賜った課題を度々投下できたら良いと思ってマース!