标签:
一个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\":\"一班\"}]";
}
标签:
原文地址:http://www.cnblogs.com/dukk/p/iis_object.html