一個c#寫的的web服務器,只進行簡單的處理HTTP請求,第一次寫,功能比較簡單,比較適合做API服務器
因為是類的方式,可以嵌入任何程序中
代碼
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Web
{
class HTTPServer
{
private const int BufferSize = 4096;
private TcpListener Tcp;
/// <summary>
/// 最多每秒請求處理次數
/// </summary>
public static int MaxRequest = 1000;
/// <summary>
/// 第一個參數是請求方式,第二個參數是請求地址,返回值為你處理好的結果
/// </summary>
public static Func<string, string, string> Response { get; set; }
/// <summary>
/// 設置消息編碼方式
/// </summary>
public static Encoding coding = Encoding.UTF8;
public HTTPServer(int port = 80)
{
//啟動監聽程序
Tcp = new TcpListener(IPAddress.Any, port);
Tcp.Start();
Console.WriteLine("服務已經啟動了");
while (true)
{
while (!Tcp.Pending())
{
Thread.Sleep(1000 / MaxRequest);
}
//啟動接受線程
ThreadStart(HandleThread);
}
}
public void HandleThread()
{
Socket socket = Tcp.AcceptSocket();
Byte[] readclientchar = new Byte[BufferSize];
int rc = socket.Receive(readclientchar, 0, BufferSize, SocketFlags.None);
string[] RequestLines = coding.GetString(readclientchar, 0, rc)
.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
string[] strs = RequestLines[0].Split(' ');
if (Response != null)
{
SendResponse(socket, Response(strs[0], strs[1]));
}
else {
SendResponse(socket, "請求成功,但是未進行任何處理");
}
socket.Close();
}
void SendResponse(Socket socket, string str)//發送文件(文件頭和內容)
{
Action<string> send = (s) => { socket.Send(coding.GetBytes(s)); };
send("HTTP/1.1 200 OK\r\n");
send("Content-Type:application/json; charset=utf-8\r\n");
send("Content-Length:" + str.Length + 2 + "\r\n");
//發送一個空行
send("\r\n");
send(str);
}
public static HTTPServer Create(int port = 80)
{
HTTPServer server = null;
ThreadStart(() => { server = new HTTPServer(port); });
return server;
}
private static void ThreadStart(Action action)
{
ThreadStart myThreadStart = new ThreadStart(action);
Thread myWorkerThread = new Thread(myThreadStart);
myWorkerThread.Start();
}
}
}
調用方式兩種
1. new HTTPServer() --------這種方式有一個弊端就是,在程序中,會阻塞當前線程,無法進行其他操作
2. HTTPServer.Create() ----這種方式在創建的適合執行的是多線程操作,可以在當前線程中繼續處理其他事
處理方法
HTTPServer中有一個委托方法Response,第一個參數是請求方式,第二個參數是請求地址,返回值為你處理好的結果
以下是示列代碼
static void Main(string[] args)
{
HTTPServer.Response = Response;
//new HTTPServer(1234);
HTTPServer ser = HTTPServer.Create(1234);
}
public static string Response(string methed, string url)
{
return "[{\"Id\":22,\"Name\":\"二班\"},{\"Id\":1,\"Name\":\"一班\"}]";
}