C# : 永遠傳回 Hello 的 WebServer

作品

書籍

課程

程式集

小說集

論文集

散文集

影片集

編輯雜誌

程式人

電子書

JavaScript

計算語言學

微積分

Blender 動畫

C# 語言

系統程式

高等 C 語言

Java

Android

Verilog

Wikidot

R 統計軟體

機率統計

計算機數學

組合語言

人工智慧

開放原始碼

網路資源運用

計算機結構

相關訊息

常用工具

友站連結

在家教育

RSS

最新修改

網頁列表

簡體版

English

簡介

程式原始碼

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

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License