-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathHttpServer.cs
227 lines (188 loc) · 6.28 KB
/
HttpServer.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Copyright (C) 2016 by David Jeske, Barend Erasmus and donated to the public domain
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;
namespace Telegram.Common
{
public delegate HttpResponse ProcessRequestCallback(HttpRequest request);
public class HttpRequest
{
public string Method { get; set; }
public string Path { get; set; }
public Dictionary<string, string> Headers { get; set; }
public HttpRequest()
{
this.Headers = new Dictionary<string, string>();
}
public override string ToString()
{
return string.Format("{0} {1} HTTP/1.0\n{2}", this.Method, this.Path, string.Join("\r\n", this.Headers.Select(x => string.Format("{0}: {1}", x.Key, x.Value))));
}
}
public class HttpResponse
{
public string StatusCode { get; set; } = "200";
public string ReasonPhrase { get; set; }
public byte[] Content { get; set; }
public Dictionary<string, string> Headers { get; set; }
public HttpResponse()
{
Headers = new Dictionary<string, string>();
}
// informational only tostring...
public override string ToString()
{
return string.Format("HTTP status {0} {1}", this.StatusCode, this.ReasonPhrase);
}
}
public class HttpServer
{
private readonly ProcessRequestCallback _callback;
private readonly int _port;
private TcpListener _listener;
private bool _active = true;
public HttpServer(int port, ProcessRequestCallback callback)
{
_callback = callback;
_port = port;
}
public void Start()
{
Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
private void Listen()
{
_listener = new TcpListener(IPAddress.Any, _port);
_listener.Start();
while (_active)
{
var connection = TryAcceptTcpClient();
if (connection != null)
{
ThreadPool.QueueUserWorkItem(state => HandleClient(connection));
}
Thread.Sleep(1);
}
}
private TcpClient TryAcceptTcpClient()
{
try
{
return _listener.AcceptTcpClient();
}
catch
{
return null;
}
}
public void Stop()
{
_active = false;
_listener.Stop();
}
#region Processor
public void HandleClient(TcpClient tcpClient)
{
try
{
Stream stream = tcpClient.GetStream();
HttpRequest request = GetRequest(stream);
// route and handle the request...
HttpResponse response = _callback(request);
Console.WriteLine("{0} {1}", response.StatusCode, request.Path);
// build a default response for errors
WriteResponse(stream, response);
stream.Flush();
stream.Close();
stream = null;
}
catch (IOException)
{
// Connection was aborted
}
}
// this formats the HTTP response...
private static void WriteResponse(Stream stream, HttpResponse response)
{
if (response.Content == null)
{
response.Content = new byte[0];
}
response.Headers["Content-Length"] = response.Content.Length.ToString();
Write(stream, string.Format("HTTP/1.0 {0} {1}\n", response.StatusCode, response.ReasonPhrase));
foreach (var header in response.Headers)
{
Write(stream, string.Format("{0}: {1}\n", header.Key, header.Value));
}
Write(stream, "\n");
stream.Write(response.Content, 0, response.Content.Length);
}
private static string ReadLine(Stream stream)
{
int next_char;
string data = "";
while (true)
{
next_char = stream.ReadByte();
if (next_char == '\n') { break; }
if (next_char == '\r') { continue; }
if (next_char == -1) { Thread.Sleep(1); continue; };
data += Convert.ToChar(next_char);
}
return data;
}
private static void Write(Stream stream, string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
private HttpRequest GetRequest(Stream stream)
{
//Read Request Line
string request = ReadLine(stream);
string[] tokens = request.Split(' ');
if (tokens.Length != 3)
{
throw new Exception("invalid http request line");
}
string method = tokens[0].ToUpper();
string resource = tokens[1];
string protocolVersion = tokens[2];
//Read Headers
Dictionary<string, string> headers = new Dictionary<string, string>();
string line;
while ((line = ReadLine(stream)) != null)
{
if (line.Equals(""))
{
break;
}
int separator = line.IndexOf(':');
if (separator == -1)
{
throw new Exception("invalid http header line: " + line);
}
string name = line.Substring(0, separator);
int pos = separator + 1;
while ((pos < line.Length) && (line[pos] == ' '))
{
pos++;
}
headers[name] = line.Substring(pos, line.Length - pos);
}
return new HttpRequest()
{
Method = method,
Path = resource.Trim('/'),
Headers = headers,
};
}
#endregion
}
}