forked from aspnet/Benchmarks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
76 lines (64 loc) · 1.93 KB
/
Program.cs
File metadata and controls
76 lines (64 loc) · 1.93 KB
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
67
68
69
70
71
72
73
74
75
76
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace BasicHttpServer
{
public class Program
{
static readonly string responseStr = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain;charset=UTF-8\r\n" +
"Content-Length: 10\r\n" +
"Connection: keep-alive\r\n" +
"Server: Dummy\r\n" +
"\r\n" +
"HelloWorld";
private static byte[] _responseBytes = Encoding.UTF8.GetBytes(responseStr);
static void Main(string[] args)
{
var ss = new Socket(SocketType.Stream, ProtocolType.Tcp);
ss.Bind(new IPEndPoint(IPAddress.Loopback, 1001));
ss.Listen(50);
ThreadPool.SetMinThreads(100, 100);
while (true)
{
var socket = ss.Accept();
ThreadPool.QueueUserWorkItem(_ => Serve(socket));
}
}
static void Serve(Socket socket)
{
socket.NoDelay = true;
try
{
var x = 0;
var buffer = new byte[2048];
while (true)
{
var stream = new NetworkStream(socket);
int r = stream.Read(buffer, 0, buffer.Length);
if (r == 0)
{
Console.WriteLine("quitting");
break;
}
for (int i = 0; i < r; i++)
{
x += buffer[i];
}
stream.Write(_responseBytes, 0, _responseBytes.Length);
stream.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
socket.Close();
}
}
}
}