-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
66 lines (58 loc) · 2.14 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace WebServer
{
internal abstract class Program
{
private const int Max = 128;
public static void Main()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var endPoint = new IPEndPoint(IPAddress.Any, 8888);
socket.Bind(endPoint);
socket.Listen(Max);
while (true)
{
var newSocket = socket.Accept();
var thread = new Thread(() => HandleClient(newSocket));
thread.Start();
}
}
private static void HandleClient(Socket socket)
{
var buffer = new byte[2048];
while (true)
{
var bytesRead = socket.Receive(buffer);
if (bytesRead == 0)
{
break;
}
var httpRequestString = Encoding.ASCII.GetString(buffer, 0, bytesRead);
// Console.WriteLine(httpRequestString);
try
{
var httpRequestMessage = HttpHelper.CreateHttpRequestMessage(httpRequestString);
var httpResponseMessage = HttpHelper.CreateHttpResponseMessage(httpRequestMessage);
// log
Console.WriteLine(HttpHelper.MakeLog(httpRequestMessage, httpResponseMessage, socket));
Debug.Assert(httpResponseMessage.Content.Headers.ContentType != null);
var httpResponseMessageString = httpResponseMessage.ToHttpResponseMessageString();
var bytesToWrite = Encoding.UTF8.GetBytes(httpResponseMessageString);
socket.Send(bytesToWrite);
if (httpRequestMessage.Headers.ConnectionClose == true)
{
break;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
socket.Close();
}
}
}