-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadedHTTPServer.cs
More file actions
264 lines (224 loc) · 7.6 KB
/
ThreadedHTTPServer.cs
File metadata and controls
264 lines (224 loc) · 7.6 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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
* Telemedycyna i Technologie Sieciowe
* Laboratorium. Gniazda sieciowe cz.2: Wielowatkowa obsluga polaczen
* Klasa serwera echo (wielowatkowy)
* v.0.1.a, 2018-03-12, Marcin.Rudzki@polsl.pl
* fork -> mini serwer HTTP: v0.1, 2018-04-20, Jacek.Kawa@polsl.pl
*/
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Web;
namespace TCPSockets2
{
class ThreadedHTTPServer : IServer
{
// klasa obslugujaca polaczenie z jednym klientem
class ClientHelper
{
Socket socket; // otwarte gniazdo polaczenia
NetworkStream ns; // strumien sieciowy "na gniezdzie"
StreamReader sr; // strumien do odbierania danych "na s.sieciowym"
StreamWriter sw; // strumien do wysylania danych "na s.sieciowym"
ThreadedHTTPServer server;
const string BaseDirectory = @"d:";
//const string BaseDirectory = @"/tmp";
public ClientHelper(Socket socket, ThreadedHTTPServer server)
{
this.socket = socket;
ns = new NetworkStream(this.socket);
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
sw.AutoFlush = true;
this.server = server;
}
// pozyczone z https://stackoverflow.com/questions/2030847/best-way-to-read-a-large-file-into-a-byte-array-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
public byte[] FileToByteArray(string fileName)
{
byte[] buff = null;
FileStream fs = new FileStream(fileName,
FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(fileName).Length;
buff = br.ReadBytes((int) numBytes);
return buff;
}
private void GET(String uri, Dictionary<String, String> headers)
{
//dalej mało eleganckie
if (uri == "/")
uri = BaseDirectory + "/index.html";
else
uri = BaseDirectory + uri.Replace(@"/", @"\");
//uri = BaseDirectory + uri;
//uri = BaseDirectory + uri;
// generuj odpowiedź
String ct = "";
switch (Path.GetExtension(uri).ToLower())
{
case "png":
ct = "image/png";
break;
case "jpg":
case "jpeg":
case "jfif":
ct = "image/jpg";
break;
case "txt":
case "text":
case "conf":
ct = "text/plain";
break;
case "html":
ct = "text/html";
break;
default:
sw.WriteLine("HTTP/1.1 503 Service Unavailable");
break;
}
byte [] content = null;
try {
content = FileToByteArray(uri);
} catch (FileNotFoundException e)
{
sw.WriteLine("HTTP/1.1 404 File Not Found");
//content length byłby wskazany
sw.WriteLine("Content-Type: text/html");
sw.WriteLine();
sw.WriteLine("<http><body>BUUU</body></html>");
return;
}
sw.WriteLine("HTTP/1.1 200 OK");
sw.WriteLine("Content-Type: " + ct);
// wypisz nagłówek długości
sw.WriteLine("Content-Length: {0}", content.Length);
// wypisz stronę/body
sw.WriteLine();
sw.BaseStream.Write(content, 0, content.Length);
}
private void POST(String uri, Dictionary<String, String> headers, byte [] body)
{
sw.WriteLine("HTTP/1.1 405 Method Not Allowed");
}
private void PUT(String uri, Dictionary<String, String> headers, byte [] body)
{
sw.WriteLine("HTTP/1.1 405 Method Not Allowed");
}
private void DELETE(String uri, Dictionary<String, String> headers)
{
sw.WriteLine("HTTP/1.1 405 Method Not Allowed");
}
public void ProcessCommunication()
{
String command = sr.ReadLine();
Regex commandProcessor = new Regex("(?<method>GET|POST|PUT|DELETE|HEAD) *(?<uri>[^ ]*) HTTP/(?<httpVersion>1.[012])");
if (command == null || !commandProcessor.IsMatch(command))
{
// brak dopasowania do komendy
sw.WriteLine("HTTP/1.1 500 INTERNAL SERVER ERROR");
Disconnect();
server.RemoveClient(this);
return;
}
Match commandParts = commandProcessor.Match(command);
// dekoduj URL/URI (odzyskaj spaje itp.)
String uri = HttpUtility.UrlDecode(commandParts.Groups["uri"].Value);
// commandParts.Groups["method"] // GET/POST/PUT/DELETE/HEAD
// commandParts.Groups["httpVersion"] //1.0, 1.1, 1.2
// dekoduj nagłówki do słownika headers
Dictionary<String,String> headers = new Dictionary<String, String>();
Regex headerProcessor = new Regex("^(?<name>[^:]*): (?<content>.*)$");
while (true)
{
String line = sr.ReadLine();
if (line.Length == 0)
break;
if (headerProcessor.IsMatch(line))
{
Match x = headerProcessor.Match(line);
headers[x.Groups["name"].Value] = x.Groups["content"].Value;
}
}
//wybierz metodę do obsługi
switch (commandParts.Groups["method"].ToString())
{
case "GET":
case "HEAD":
GET(uri, headers);
break;
case "DELETE":
DELETE(uri, headers);
break;
case "POST":
POST(uri, headers, null);
break;
case "PUT":
PUT(uri, headers, null);
break;
default:
throw new Exception("unknown method " + commandParts.Groups["method"]);
};
sw.Flush();
// bye bye
Disconnect();
server.RemoveClient(this);
}
void Disconnect()
{
// to nie sprawdza czy strumien jest juz Disposed...
if (sw != null) sw.Close();
if (sr != null) sr.Close();
if (ns != null) ns.Close();
if (socket != null) socket.Close();
}
}
IPEndPoint ipEndPoint;
Socket listeningSocket;
List<ClientHelper> activeClients;
public ThreadedHTTPServer(IPAddress ipAddress, int ipPort)
{
ipEndPoint = new IPEndPoint(ipAddress, ipPort);
listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Console.WriteLine("Server created.");
activeClients = new List<ClientHelper>();
}
public void Start()
{
listeningSocket.Bind(ipEndPoint);
listeningSocket.Listen(1);
Console.WriteLine("Server @ {0} started.", ipEndPoint);
do
{
Console.WriteLine("Server @ {0} waits for a client...", ipEndPoint);
Socket clientSocket = listeningSocket.Accept(); // czy to moze zglosic wyjatek?
Console.WriteLine("Server @ {0} client connected @ {1}.", ipEndPoint, clientSocket.RemoteEndPoint);
Console.WriteLine("Server @ {0} starting client thread.", ipEndPoint, clientSocket.RemoteEndPoint);
// stworz obiekt obslugujacy polaczenie z klientem
ClientHelper ch = new ClientHelper(clientSocket, this);
activeClients.Add(ch);
// stworz nowy watek, przekaz w ctorze metode, ktora ma byc uruchomiona
Thread t = new Thread(ch.ProcessCommunication);
// uruchom watek (przekazana w ctorze metode)
t.Start();
// ... i... zapomnij o tym (?)
}
while (true);
}
void RemoveClient(ClientHelper ch)
{
activeClients.Remove(ch);
}
public void Stop()
{
listeningSocket.Close();
// a co z ew. klientami?
}
} // class
} // namespace