C# : 永遠傳回 Hello 的 WebServer

基礎篇

C# 簡介

開發環境

變數與運算

流程控制

陣列

函數

物件

例外處理

函式庫篇

檔案處理

資料結構

正規表達式

Thread

應用篇

視窗程式

媒體影音

網路程式

遊戲程式

手機程式

資料庫

雲端運算

特殊功能

委派

擴展方法

序列化

LinQ

WPF

網路資源

教學影片

投影片

教學文章

軟體下載

考題解答

101習題

簡介

程式原始碼

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO;

public class HttpServer
{
    public static void Main()
    {
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 80);

        Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        newsock.Bind(ipep);
        newsock.Listen(10);

        while(true)
        {
         Socket client = newsock.Accept();
         IPEndPoint clientep = (IPEndPoint) client.RemoteEndPoint;

         // create a new thread and then receive message.
         HttpListener listener = new HttpListener(client);
         Thread thread = new Thread(new ThreadStart(listener.run));
         thread.Start();
        }
//      newsock.Close();
   }
}

public class HttpListener {
    Socket socket;

    public HttpListener(Socket s)
    {
        socket = s;
    }

    public void run() 
    {
        String msg = "Hello!";
        String helloMsg = @"HTTP/1.0 200 OK\nContent-Type: text/plain\nContgent-Length: "+msg.Length+"\n\n"+msg;

        NetworkStream stream = new NetworkStream(socket);
        StreamReader reader = new StreamReader(stream);
        String header = "";
        while (true) 
        {
         String line = reader.ReadLine();
         Console.WriteLine(line);
         if (line.Trim().Length==0)
         break;
         header += line+"\n";
        }
        socket.Send(Encoding.UTF8.GetBytes(helloMsg));
        socket.Close();
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License