2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】HttpListenerで簡易サーバー作成する

Last updated at Posted at 2019-08-21

備忘録とMarkdown記法に慣れる練習兼ねて。

D01tsumaTask1.cs

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);
            }
        }
    }
}

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?