今天偶尔遇到需要用socket类,封装了一个简单web server
使用方法:
HttpServer hs = new HttpServer(IPAddress.Any, 16888,"d:/web", 10);//最后一个参数为队列长度(最多同时运行几个连接)
hs.StartServer();然后可以用浏览器访问http://local:16888/index.html 或者 http://127.0.0.1:16888/index.html访问了需要的namespace:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;服务器类:
class HttpServer
{
private Socket socketmain;
private string ServerPath;
private Dictionary<string, string> extensions = new Dictionary<string, string>()
{
//{ "extension", "content type" }
{ "htm", "text/html" },
{ "html", "text/html" },
{ "xml", "text/xml" },
{ "txt", "text/plain" },
{ "css", "text/css" },
{ "png", "image/png" },
{ "gif", "image/gif" },
{ "jpg", "image/jpg" },
{ "jpeg", "image/jpeg" },
{ "zip", "application/zip"},
{ "rar", "application/rar"}
};
private void Send(Socket socketChildren, string filename)
{
string ex = Path.GetExtension(filename).Substring(1);
if (extensions.ContainsKey(ex))
{
if (File.Exists(ServerPath + filename))
{
byte[] bytes2 = File.ReadAllBytes(ServerPath + filename);
sendResponse(socketChildren, bytes2, "200", extensions[ex]);
}
else
{
byte[] bytes = Encoding.UTF8.GetBytes("HELLO!NO FOUND:" + filename);
sendResponse(socketChildren, bytes, "404", "text/html");
}
}
else
{
byte[] bytes = Encoding.UTF8.GetBytes("HELLO!NO FOUND:" + filename);
sendResponse(socketChildren, bytes, "404", "text/html");
}
}
private void sendResponse(Socket clientSocket, byte[] bContent, string responseCode,
string contentType)
{
try
{
byte[] bHeader = Encoding.UTF8.GetBytes(
"HTTP/1.1 " + responseCode + "\r\n"
+ "Server: X Server v1.0\r\n"
+ "Content-Length: " + bContent.Length.ToString() + "\r\n"
+ "Connection: close\r\n"
+ "Content-Type: " + contentType + "\r\n\r\n");
clientSocket.Send(bHeader);
clientSocket.Send(bContent);
clientSocket.Close();
}
catch { }
}
public HttpServer(IPAddress ip, int port,string ServerPath, int RanksLength)
{
this.ServerPath = ServerPath;
socketmain = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketmain.Bind(new IPEndPoint(ip, port));
socketmain.Listen(RanksLength);
}
public void StartServer()
{
Thread t = new Thread(Run);
t.IsBackground = true;
t.Start();
}
private void Run(object obj)
{
while (true)
{
Socket socketChildren = socketmain.Accept();
Thread t = new Thread(OpenConn);
t.IsBackground = true;
t.Start(socketChildren);
}
}
private void OpenConn(object obj)
{
Socket socketChildren = obj as Socket;
while (true)
{
if (socketChildren.Connected == false)
break;
byte[] bts = new byte[1024 * 1024 * 5];
int p = socketChildren.Receive(bts);
string data = Encoding.UTF8.GetString(bts, 0, p);
string filename = data.Substring(data.IndexOf("GET /") + 5).Substring(0, data.IndexOf(" HTTP/1.1") - 5);
Send(socketChildren, filename);
}
}
}版权声明:本文为u013555095原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。