Revize 6d0d1410
Přidáno uživatelem Eliška Mourycová před více než 3 roky(ů)
Server/ServerApp/Connection/ConnectionListener.cs | ||
---|---|---|
1 |
// |
|
2 |
// Author: Eliska Mourycova |
|
3 |
// |
|
4 |
|
|
5 |
using ServerApp.Connection.XMLProtocolHandler; |
|
6 |
using System; |
|
7 |
using System.Collections.Generic; |
|
8 |
using System.IO; |
|
9 |
using System.Net; |
|
10 |
using System.Net.Sockets; |
|
11 |
using System.Text; |
|
12 |
using System.Threading; |
|
13 |
using System.Web; |
|
14 |
|
|
15 |
namespace ServerApp.Connection |
|
16 |
{ |
|
17 |
// /// <summary> |
|
18 |
// /// State object for reading client data asynchronously |
|
19 |
// /// </summary> |
|
20 |
// public class StateObject |
|
21 |
// { |
|
22 |
// // Client socket. |
|
23 |
// public Socket WorkSocket = null; |
|
24 |
// // Size of receive buffer. |
|
25 |
// public const int BUFFER_SIZE = 1024; |
|
26 |
// // Receive buffer. |
|
27 |
// public byte[] Buffer = new byte[BUFFER_SIZE]; |
|
28 |
// // Received data string. |
|
29 |
// public StringBuilder StrBuilder = new StringBuilder(); |
|
30 |
// } |
|
31 |
|
|
32 |
// /// <summary> |
|
33 |
// /// This class takes care of client connection. It serves clients asynchronously. |
|
34 |
// /// </summary> |
|
35 |
// public class AsynchronousSocketListener |
|
36 |
// { |
|
37 |
// // port numbers: |
|
38 |
// private const int PORT_NO = 11000; |
|
39 |
// private const int ADMIN_PORT_NO = 10000; |
|
40 |
|
|
41 |
|
|
42 |
// // Thread signal |
|
43 |
// private ManualResetEvent allDone = new ManualResetEvent(false); |
|
44 |
|
|
45 |
// /// <summary> |
|
46 |
// /// Starts listening and accepting connections. It serves requests when they come. |
|
47 |
// /// </summary> |
|
48 |
// public void StartListening() |
|
49 |
// { |
|
50 |
// // Data buffer for incoming data. |
|
51 |
// byte[] bytes = new Byte[1024]; |
|
52 |
|
|
53 |
// // Establish the local endpoint for the socket: |
|
54 |
// IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); |
|
55 |
|
|
56 |
// // Get the IP of the machine - UNUSED ATM, USING LOOPBACK ON LOCALHOST |
|
57 |
// IPAddress ipAddress = ipHostInfo.AddressList[1]; |
|
58 |
// Console.WriteLine("machine ip: " + ipAddress.ToString()); |
|
59 |
// IPEndPoint localEndPoint = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, PORT_NO); |
|
60 |
// IPEndPoint localEndPointAdmin = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, ADMIN_PORT_NO); |
|
61 |
|
|
62 |
// // Create a TCP/IP socket. |
|
63 |
// Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
|
64 |
// Socket listenerAdmin = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
|
65 |
|
|
66 |
// // Bind the socket to the local endpoint and listen for incoming connections. |
|
67 |
// try |
|
68 |
// { |
|
69 |
// listener.Bind(localEndPoint); |
|
70 |
// listener.Listen(100); |
|
71 |
|
|
72 |
// listenerAdmin.Bind(localEndPointAdmin); |
|
73 |
// listenerAdmin.Listen(1); |
|
74 |
|
|
75 |
// // keep accepting |
|
76 |
// while (true) |
|
77 |
// { |
|
78 |
// // Set the event to nonsignaled state. |
|
79 |
// allDone.Reset(); |
|
80 |
|
|
81 |
// // Start an asynchronous socket to listen for connections. |
|
82 |
// Console.WriteLine("Waiting for a connection..."); |
|
83 |
// listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); |
|
84 |
// listenerAdmin.BeginAccept(new AsyncCallback(AcceptCallback), listenerAdmin); |
|
85 |
|
|
86 |
// // Wait until a connection is made before continuing. |
|
87 |
// allDone.WaitOne(); |
|
88 |
// } |
|
89 |
|
|
90 |
// } |
|
91 |
// catch (Exception e) |
|
92 |
// { |
|
93 |
// // bind failed |
|
94 |
// Console.WriteLine(e.ToString()); |
|
95 |
// } |
|
96 |
|
|
97 |
// Console.WriteLine("\nPress ENTER to continue..."); |
|
98 |
// Console.Read(); |
|
99 |
|
|
100 |
// } |
|
101 |
|
|
102 |
// // Routine for when BeginAccept on the given listener ended |
|
103 |
// private void AcceptCallback(IAsyncResult ar) |
|
104 |
// { |
|
105 |
// // Signal the main thread to continue. |
|
106 |
// allDone.Set(); |
|
107 |
// Console.WriteLine("Accepted a connection."); |
|
108 |
|
|
109 |
|
|
110 |
// // Get the socket that handles the client request. |
|
111 |
// Socket listener = (Socket)ar.AsyncState; |
|
112 |
// Socket handler = listener.EndAccept(ar); |
|
113 |
|
|
114 |
// // debug |
|
115 |
// Console.WriteLine("handler: "); |
|
116 |
// Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)handler.RemoteEndPoint).Address.ToString()) + " on port number " + ((IPEndPoint)handler.RemoteEndPoint).Port.ToString()); |
|
117 |
// Console.WriteLine("My local IpAddress is : " + IPAddress.Parse(((IPEndPoint)handler.LocalEndPoint).Address.ToString()) + ". I am connected on port number " + ((IPEndPoint)handler.LocalEndPoint).Port.ToString()); |
|
118 |
|
|
119 |
|
|
120 |
|
|
121 |
|
|
122 |
// // Create the state object. |
|
123 |
// StateObject state = new StateObject(); |
|
124 |
// state.WorkSocket = handler; |
|
125 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
126 |
|
|
127 |
// } |
|
128 |
|
|
129 |
// // Routine for when BeginReceive on the given listener ended |
|
130 |
// private void ReadCallback(IAsyncResult ar) |
|
131 |
// { |
|
132 |
// // string for the received message |
|
133 |
// String content = String.Empty; |
|
134 |
|
|
135 |
// // Retrieve the state object and the handler socket |
|
136 |
// // from the asynchronous state object. |
|
137 |
// StateObject state = (StateObject)ar.AsyncState; |
|
138 |
// Socket handler = state.WorkSocket; |
|
139 |
|
|
140 |
// // check if we're still connected |
|
141 |
// if (!SocketConnected(handler)) |
|
142 |
// { |
|
143 |
// // if the client isn't connected anymore, take care of cleanup |
|
144 |
// Console.WriteLine("Closing connection - unexpected..."); |
|
145 |
// CloseConnection(handler); |
|
146 |
|
|
147 |
// // return so that we don't attempt to read from a non-existent stream |
|
148 |
// return; |
|
149 |
// } |
|
150 |
|
|
151 |
// // check if it is admin's request we're serving |
|
152 |
// bool admin = ((IPEndPoint)handler.LocalEndPoint).Port == ADMIN_PORT_NO; |
|
153 |
|
|
154 |
// // Read data from the client socket. |
|
155 |
// int bytesRead = handler.EndReceive(ar); |
|
156 |
|
|
157 |
// if (bytesRead > 0) |
|
158 |
// { |
|
159 |
// // There might be more data, so store the data received so far. |
|
160 |
// state.StrBuilder.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead)); |
|
161 |
|
|
162 |
// // Check for end-of-file tag. If it is not there, read more data. |
|
163 |
// content = state.StrBuilder.ToString(); |
|
164 |
// if (content.IndexOf("!") > -1) |
|
165 |
// { |
|
166 |
// // All the data has been read from the client. Display it on the console. |
|
167 |
// Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); |
|
168 |
|
|
169 |
// // parse the message and determine the response: |
|
170 |
// content = ParseMessageAndBuildAnswer(content, admin); |
|
171 |
|
|
172 |
// // check if the client wishes to close the connection: |
|
173 |
// if (content.Equals("bye!")) |
|
174 |
// { |
|
175 |
// Console.WriteLine("Closing connection - expected..."); |
|
176 |
// //handler.Shutdown(SocketShutdown.Both); |
|
177 |
// //handler.Close(); |
|
178 |
// CloseConnection(handler); |
|
179 |
// return; |
|
180 |
// } |
|
181 |
|
|
182 |
// // Send a response to the client |
|
183 |
// Send(handler, content); |
|
184 |
|
|
185 |
// // clear the string |
|
186 |
// state.StrBuilder.Clear(); |
|
187 |
|
|
188 |
// // begin receiving another message: |
|
189 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
190 |
// } |
|
191 |
// else |
|
192 |
// { |
|
193 |
// // Not all data received. Get more. |
|
194 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
195 |
// } |
|
196 |
// } |
|
197 |
// } |
|
198 |
|
|
199 |
// // Takes care of sending data to a connected client |
|
200 |
// private void Send(Socket handler, String data) |
|
201 |
// { |
|
202 |
// // Convert the string data to byte data using ASCII encoding. |
|
203 |
// byte[] byteData = Encoding.ASCII.GetBytes(data); |
|
204 |
|
|
205 |
// // Begin sending the data to the remote device. |
|
206 |
// handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); |
|
207 |
// } |
|
208 |
|
|
209 |
// // Routine for when BeginSend on the given listener ended |
|
210 |
// private void SendCallback(IAsyncResult ar) |
|
211 |
// { |
|
212 |
// try |
|
213 |
// { |
|
214 |
// // Retrieve the socket from the state object. |
|
215 |
// Socket handler = (Socket)ar.AsyncState; |
|
216 |
|
|
217 |
// // Complete sending the data to the remote device. |
|
218 |
// int bytesSent = handler.EndSend(ar); |
|
219 |
// Console.WriteLine("Sent {0} bytes to client.", bytesSent); |
|
220 |
|
|
221 |
|
|
222 |
// //handler.Shutdown(SocketShutdown.Both); |
|
223 |
// //handler.Close(); |
|
224 |
|
|
225 |
// } |
|
226 |
// catch (Exception e) |
|
227 |
// { |
|
228 |
// // close connection here? |
|
229 |
|
|
230 |
// Console.WriteLine(e.ToString()); |
|
231 |
// } |
|
232 |
// } |
|
233 |
|
|
234 |
|
|
235 |
// /// <summary> |
|
236 |
// /// Parses the incoming request and determines the response. |
|
237 |
// /// </summary> |
|
238 |
// /// <param name="message">The incoming message from the client</param> |
|
239 |
// /// <param name="admin">A flag saying whether it is admin's request</param> |
|
240 |
// /// <returns></returns> |
|
241 |
// private string ParseMessageAndBuildAnswer(string message, bool admin) |
|
242 |
//{ |
|
243 |
// Console.WriteLine("Parsing message from admin: " + admin); |
|
244 |
// string ans = ""; |
|
245 |
|
|
246 |
// if (message.Equals("hello!")) |
|
247 |
// { |
|
248 |
// ans = "hello to you too."; |
|
249 |
// } |
|
250 |
// else if (message.Equals("weather!")) |
|
251 |
// { |
|
252 |
// ans = "weather will be nice"; |
|
253 |
// } |
|
254 |
// else if (message.Equals("bye!")) |
|
255 |
// { |
|
256 |
// ans = "bye!"; |
|
257 |
// } |
|
258 |
// else |
|
259 |
// { |
|
260 |
// // here bye too, if we want to disconnect clients who don't follow protocol |
|
261 |
// ans = "bye!";//"i didnt understand that"; |
|
262 |
|
|
263 |
// } |
|
264 |
|
|
265 |
// return ans; |
|
266 |
//} |
|
267 |
|
|
268 |
// /// <summary> |
|
269 |
// /// Closes the connection on the passed Socket |
|
270 |
// /// </summary> |
|
271 |
// /// <param name="s">The socket to close the connection for</param> |
|
272 |
// private void CloseConnection(Socket s) |
|
273 |
//{ |
|
274 |
// s.Shutdown(SocketShutdown.Both); |
|
275 |
// s.Close(); |
|
276 |
// } |
|
277 |
|
|
278 |
// /// <summary> |
|
279 |
// /// Checks whether the connection on a given socket is active |
|
280 |
// /// </summary> |
|
281 |
// /// <param name="s">The socket to check for connection activity</param> |
|
282 |
// /// <returns>True if the connection is active, false otherwise</returns> |
|
283 |
// private bool SocketConnected(Socket s) |
|
284 |
// { |
|
285 |
// bool part1 = s.Poll(1000, SelectMode.SelectRead); |
|
286 |
// bool part2 = (s.Available == 0); |
|
287 |
// if (part1 && part2) |
|
288 |
// return false; |
|
289 |
// else |
|
290 |
// return true; |
|
291 |
// } |
|
292 |
// } |
|
293 |
|
|
294 |
|
|
295 |
class ClientService |
|
296 |
{ |
|
297 |
int id; |
|
298 |
Request request; |
|
299 |
Response response; |
|
300 |
} |
|
301 |
|
|
302 |
public class ConnectionListener |
|
303 |
{ |
|
304 |
private readonly int PORT; |
|
305 |
private Dictionary<int, ClientService> allRequests; |
|
306 |
private Queue<Request> waitingRequests; |
|
307 |
|
|
308 |
|
|
309 |
public ConnectionListener(int port) |
|
310 |
{ |
|
311 |
this.PORT = port; |
|
312 |
} |
|
313 |
|
|
314 |
public void StartListening() |
|
315 |
{ |
|
316 |
string ip = GetLocalIPAddress(); |
|
317 |
Console.WriteLine("ip : " + ip); |
|
318 |
HttpListener server = new HttpListener(); |
|
319 |
//server.Prefixes.Add($"http://*:1234/work/"); |
|
320 |
server.Prefixes.Add($"https://{ip}:{PORT}/"); |
|
321 |
//server.Prefixes.Add($"http://localhost:{PORT}/work/"); |
|
322 |
//server.Prefixes.Add($"http://127.0.0.1:{PORT}/work/"); |
|
323 |
//server.Prefixes.Add($"http://{ip}:{PORT}/work/"); |
|
324 |
//server.Prefixes.Add($"http://+:{PORT}/work/"); |
|
325 |
|
|
326 |
server.Start(); |
|
327 |
|
|
328 |
Console.WriteLine("Listening..."); |
|
329 |
|
|
330 |
while (true) |
|
331 |
{ |
|
332 |
Console.WriteLine("waiting for request?"); |
|
333 |
//Console.ReadLine(); |
|
334 |
|
|
335 |
HttpListenerContext context = server.GetContext(); |
|
336 |
|
|
337 |
|
|
338 |
|
|
339 |
if (context.Request.HttpMethod == "GET") // when client says download |
|
340 |
{ |
|
341 |
Console.WriteLine("received GET request"); |
|
342 |
|
|
343 |
HttpListenerResponse response = context.Response; |
|
344 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
345 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
346 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
347 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
348 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); |
|
349 |
//response.AddHeader("Access-Control-Allow-Origin", "https://kacerekz.github.io/KIV-ASWI/"); |
|
350 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
351 |
|
|
352 |
|
|
353 |
|
|
354 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; |
|
355 |
// if (page == string.Empty) |
|
356 |
// page = "test.txt"; |
|
357 |
// |
|
358 |
// TextReader tr = new StreamReader(page); |
|
359 |
// string msg = tr.ReadToEnd(); |
|
360 |
|
|
361 |
int rand = new Random().Next(1, 10); |
|
362 |
string msg = "This is a response from the server :) " + rand; |
|
363 |
|
|
364 |
Response xmlResp = Response.Randomize(); |
|
365 |
var xml = XmlCommunication.Serialize(xmlResp); |
|
366 |
//Console.WriteLine(xml); |
|
367 |
|
|
368 |
msg = xml; |
|
369 |
|
|
370 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
371 |
|
|
372 |
response.ContentLength64 = buffer.Length; |
|
373 |
Stream st = response.OutputStream; |
|
374 |
st.Write(buffer, 0, buffer.Length); |
|
375 |
|
|
376 |
|
|
377 |
context.Response.Close(); |
|
378 |
} |
|
379 |
|
|
380 |
else if (context.Request.HttpMethod == "POST") // when client says upload |
|
381 |
{ |
|
382 |
Console.WriteLine("received POST request"); |
|
383 |
|
|
384 |
string text; |
|
385 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) |
|
386 |
text = reader.ReadToEnd(); |
|
387 |
Console.WriteLine("Received request:"); |
|
388 |
Console.WriteLine(HttpUtility.UrlDecode(text)); |
|
389 |
|
|
390 |
|
|
391 |
|
|
392 |
HttpListenerResponse response = context.Response; |
|
393 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
394 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
395 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
396 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
397 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
398 |
|
|
399 |
|
|
400 |
|
|
401 |
int rand = new Random().Next(1, 10); |
|
402 |
string msg = "OK " + rand; |
|
403 |
|
|
404 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
405 |
|
|
406 |
response.ContentLength64 = buffer.Length; |
|
407 |
Stream st = response.OutputStream; |
|
408 |
st.Write(buffer, 0, buffer.Length); |
|
409 |
|
|
410 |
|
|
411 |
context.Response.Close(); // ?? Works better with this, if this line is absent, the client gets 'stuck' after approximately 6 messages |
|
412 |
} |
|
413 |
else |
|
414 |
{ |
|
415 |
Console.WriteLine("received request other than GET or POST"); |
|
416 |
Console.WriteLine("method: " + context.Request.HttpMethod); |
|
417 |
Console.WriteLine("headers: " + context.Request.Headers); |
|
418 |
Console.WriteLine("whole request?: " + context.Request); |
|
419 |
Console.WriteLine("user: " + context.User); |
|
420 |
|
|
421 |
|
|
422 |
|
|
423 |
//HttpListenerResponse response = context.Response; |
|
424 |
//response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
425 |
//response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
426 |
//response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time, Origin, Content-Type, X-Auth-Token"); |
|
427 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
428 |
//response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
429 |
|
|
430 |
//string msg = "Preflight check? "; |
|
431 |
|
|
432 |
//byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
433 |
|
|
434 |
//response.ContentLength64 = buffer.Length; |
|
435 |
//Stream st = response.OutputStream; |
|
436 |
//st.Write(buffer, 0, buffer.Length); |
|
437 |
|
|
438 |
|
|
439 |
//context.Response.Close(); // ?? |
|
440 |
|
|
441 |
} |
|
442 |
} |
|
443 |
} |
|
444 |
|
|
445 |
|
|
446 |
private string GetLocalIPAddress() |
|
447 |
{ |
|
448 |
var host = Dns.GetHostEntry(Dns.GetHostName()); |
|
449 |
foreach (var ip in host.AddressList) |
|
450 |
{ |
|
451 |
if (ip.AddressFamily == AddressFamily.InterNetwork) |
|
452 |
{ |
|
453 |
return ip.ToString(); |
|
454 |
} |
|
455 |
} |
|
456 |
throw new Exception("No network adapters with an IPv4 address in the system!"); |
|
457 |
} |
|
458 |
|
|
459 |
} |
|
460 |
|
|
461 |
} |
Server/ServerApp/Connection/ConnectionListenerMulti.cs | ||
---|---|---|
1 |
// |
|
2 |
// Author: Eliska Mourycova |
|
3 |
// |
|
4 |
|
|
5 |
using ServerApp.Connection.XMLProtocolHandler; |
|
6 |
using System; |
|
7 |
using System.Collections.Concurrent; |
|
8 |
using System.Collections.Generic; |
|
9 |
using System.IO; |
|
10 |
using System.Net; |
|
11 |
using System.Net.Sockets; |
|
12 |
using System.Text; |
|
13 |
using System.Threading; |
|
14 |
using System.Web; |
|
15 |
|
|
16 |
namespace ServerApp.Connection |
|
17 |
{ |
|
18 |
|
|
19 |
//public class HttpListenerCallbackState |
|
20 |
//{ |
|
21 |
// private readonly HttpListener _listener; |
|
22 |
// private readonly AutoResetEvent _listenForNextRequest; |
|
23 |
|
|
24 |
// public HttpListenerCallbackState(HttpListener listener) |
|
25 |
// { |
|
26 |
// if (listener == null) throw new ArgumentNullException("listener"); |
|
27 |
// _listener = listener; |
|
28 |
// _listenForNextRequest = new AutoResetEvent(false); |
|
29 |
// } |
|
30 |
|
|
31 |
// public HttpListener Listener { get { return _listener; } } |
|
32 |
// public AutoResetEvent ListenForNextRequest { get { return _listenForNextRequest; } } |
|
33 |
//} |
|
34 |
|
|
35 |
//public class HttpRequestHandler |
|
36 |
//{ |
|
37 |
// private int requestCounter = 0; |
|
38 |
// private ManualResetEvent stopEvent = new ManualResetEvent(false); |
|
39 |
// private int PORT; |
|
40 |
|
|
41 |
// public HttpRequestHandler(int port) |
|
42 |
// { |
|
43 |
// this.PORT = port; |
|
44 |
// } |
|
45 |
|
|
46 |
// public void ListenAsynchronously(/*IEnumerable<string> prefixes*/) |
|
47 |
// { |
|
48 |
// HttpListener listener = new HttpListener(); |
|
49 |
|
|
50 |
// //foreach (string s in prefixes) |
|
51 |
// //{ |
|
52 |
// // listener.Prefixes.Add(s); |
|
53 |
// //} |
|
54 |
|
|
55 |
// listener.Prefixes.Add($"http://localhost:{PORT}/"); |
|
56 |
|
|
57 |
// listener.Start(); |
|
58 |
// Console.WriteLine("Listening..."); |
|
59 |
// HttpListenerCallbackState state = new HttpListenerCallbackState(listener); |
|
60 |
// ThreadPool.QueueUserWorkItem(Listen, state); |
|
61 |
// } |
|
62 |
|
|
63 |
// public void StopListening() |
|
64 |
// { |
|
65 |
// stopEvent.Set(); |
|
66 |
// } |
|
67 |
|
|
68 |
|
|
69 |
// private void Listen(object state) |
|
70 |
// { |
|
71 |
// HttpListenerCallbackState callbackState = (HttpListenerCallbackState)state; |
|
72 |
|
|
73 |
// while (callbackState.Listener.IsListening) |
|
74 |
// { |
|
75 |
// callbackState.Listener.BeginGetContext(new AsyncCallback(ListenerCallback), callbackState); |
|
76 |
// int n = WaitHandle.WaitAny(new WaitHandle[] { callbackState.ListenForNextRequest, stopEvent }); |
|
77 |
|
|
78 |
// if (n == 1) |
|
79 |
// { |
|
80 |
// // stopEvent was signalled |
|
81 |
// callbackState.Listener.Stop(); |
|
82 |
// break; |
|
83 |
// } |
|
84 |
// } |
|
85 |
// } |
|
86 |
|
|
87 |
// private void ListenerCallback(IAsyncResult ar) |
|
88 |
// { |
|
89 |
// HttpListenerCallbackState callbackState = (HttpListenerCallbackState)ar.AsyncState; |
|
90 |
// HttpListenerContext context = null; |
|
91 |
|
|
92 |
// int requestNumber = Interlocked.Increment(ref requestCounter); |
|
93 |
|
|
94 |
// try |
|
95 |
// { |
|
96 |
// context = callbackState.Listener.EndGetContext(ar); |
|
97 |
// } |
|
98 |
// catch (Exception ex) |
|
99 |
// { |
|
100 |
// return; |
|
101 |
// } |
|
102 |
// finally |
|
103 |
// { |
|
104 |
// callbackState.ListenForNextRequest.Set(); |
|
105 |
// } |
|
106 |
|
|
107 |
// if (context == null) return; |
|
108 |
|
|
109 |
|
|
110 |
// HttpListenerRequest request = context.Request; |
|
111 |
|
|
112 |
// if (request.HasEntityBody) |
|
113 |
// { |
|
114 |
// using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)) |
|
115 |
// { |
|
116 |
// string requestData = sr.ReadToEnd(); |
|
117 |
|
|
118 |
// //Stuff I do with the request happens here |
|
119 |
// } |
|
120 |
// } |
|
121 |
|
|
122 |
|
|
123 |
// try |
|
124 |
// { |
|
125 |
// using (HttpListenerResponse response = context.Response) |
|
126 |
// { |
|
127 |
// Console.WriteLine("dealing with response"); |
|
128 |
// //Thread.Sleep(10000); |
|
129 |
// //response stuff happens here |
|
130 |
// string responseString = "Ok"; |
|
131 |
|
|
132 |
// byte[] buffer = Encoding.UTF8.GetBytes(responseString); |
|
133 |
// response.ContentLength64 = buffer.LongLength; |
|
134 |
// response.OutputStream.Write(buffer, 0, buffer.Length); |
|
135 |
// response.Close(); |
|
136 |
// } |
|
137 |
// } |
|
138 |
// catch (Exception e) |
|
139 |
// { |
|
140 |
// } |
|
141 |
// } |
|
142 |
//} |
|
143 |
|
|
144 |
|
|
145 |
|
|
146 |
|
|
147 |
|
|
148 |
|
|
149 |
|
|
150 |
|
|
151 |
|
|
152 |
|
|
153 |
public class ConnectionListener |
|
154 |
{ |
|
155 |
private readonly int PORT; |
|
156 |
|
|
157 |
public ConnectionListener(int port) |
|
158 |
{ |
|
159 |
this.PORT = port; |
|
160 |
} |
|
161 |
|
|
162 |
public void StartListening() |
|
163 |
{ |
|
164 |
string ip = GetLocalIPAddress(); |
|
165 |
Console.WriteLine("ip : " + ip); |
|
166 |
HttpListener server = new HttpListener(); |
|
167 |
//server.Prefixes.Add($"https://{ip}:{PORT}/"); |
|
168 |
server.Prefixes.Add($"http://localhost:{PORT}/"); |
|
169 |
|
|
170 |
server.Start(); |
|
171 |
|
|
172 |
Console.WriteLine("Listening..."); |
|
173 |
|
|
174 |
while (true) |
|
175 |
{ |
|
176 |
Console.WriteLine("Waiting for a client request..."); |
|
177 |
|
|
178 |
HttpListenerContext context = server.GetContext(); |
|
179 |
|
|
180 |
|
|
181 |
|
|
182 |
if (context.Request.HttpMethod == "GET") // when client says download |
|
183 |
{ |
|
184 |
Console.WriteLine("received GET request"); |
|
185 |
|
|
186 |
HttpListenerResponse response = context.Response; |
|
187 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
188 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
189 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
190 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
191 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
192 |
|
|
193 |
|
|
194 |
|
|
195 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; |
|
196 |
// if (page == string.Empty) |
|
197 |
// page = "test.txt"; |
|
198 |
// |
|
199 |
// TextReader tr = new StreamReader(page); |
|
200 |
// string msg = tr.ReadToEnd(); |
|
201 |
|
|
202 |
int rand = new Random().Next(1, 10); |
|
203 |
string msg = "This is a response from the server :) " + rand; |
|
204 |
|
|
205 |
Response xmlResp = Response.Randomize(); |
|
206 |
var xml = XmlCommunication.Serialize(xmlResp); |
|
207 |
//Console.WriteLine(xml); |
|
208 |
|
|
209 |
msg = xml; |
|
210 |
|
|
211 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
212 |
|
|
213 |
response.ContentLength64 = buffer.Length; |
|
214 |
Stream st = response.OutputStream; |
|
215 |
st.Write(buffer, 0, buffer.Length); |
|
216 |
|
|
217 |
|
|
218 |
context.Response.Close(); |
|
219 |
} |
|
220 |
|
|
221 |
else if (context.Request.HttpMethod == "POST") // when client says upload |
|
222 |
{ |
|
223 |
Console.WriteLine("received POST request"); |
|
224 |
|
|
225 |
string text; |
|
226 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) |
|
227 |
text = reader.ReadToEnd(); |
|
228 |
Console.WriteLine("Received request:"); |
|
229 |
string requestXML = HttpUtility.UrlDecode(text); |
|
230 |
Console.WriteLine(requestXML); |
|
231 |
|
|
232 |
Request newRequest = new Request(); |
|
233 |
Request requestDeserialized = XmlCommunication.Deserialize(newRequest, requestXML); |
|
234 |
|
|
235 |
HttpListenerResponse response = context.Response; |
|
236 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
237 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
238 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
239 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
240 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
241 |
|
|
242 |
|
|
243 |
|
|
244 |
int rand = new Random().Next(1, 10); |
|
245 |
string msg = "OK " + rand; |
|
246 |
|
|
247 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
248 |
|
|
249 |
response.ContentLength64 = buffer.Length; |
|
250 |
Stream st = response.OutputStream; |
|
251 |
st.Write(buffer, 0, buffer.Length); |
|
252 |
|
|
253 |
|
|
254 |
context.Response.Close(); // ?? Works better with this, if this line is absent, the client gets 'stuck' after approximately 6 messages |
|
255 |
} |
|
256 |
else |
|
257 |
{ |
|
258 |
Console.WriteLine("received request other than GET or POST"); |
|
259 |
Console.WriteLine("method: " + context.Request.HttpMethod); |
|
260 |
Console.WriteLine("headers: " + context.Request.Headers); |
|
261 |
Console.WriteLine("whole request?: " + context.Request); |
|
262 |
Console.WriteLine("user: " + context.User); |
|
263 |
|
|
264 |
|
|
265 |
|
|
266 |
//HttpListenerResponse response = context.Response; |
|
267 |
//response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
268 |
//response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
269 |
//response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time, Origin, Content-Type, X-Auth-Token"); |
|
270 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
271 |
//response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
272 |
|
|
273 |
//string msg = "Preflight check? "; |
|
274 |
|
|
275 |
//byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
276 |
|
|
277 |
//response.ContentLength64 = buffer.Length; |
|
278 |
//Stream st = response.OutputStream; |
|
279 |
//st.Write(buffer, 0, buffer.Length); |
|
280 |
|
|
281 |
|
|
282 |
//context.Response.Close(); // ?? |
|
283 |
|
|
284 |
} |
|
285 |
} |
|
286 |
} |
|
287 |
|
|
288 |
private string GetLocalIPAddress() |
|
289 |
{ |
|
290 |
var host = Dns.GetHostEntry(Dns.GetHostName()); |
|
291 |
foreach (var ip in host.AddressList) |
|
292 |
{ |
|
293 |
if (ip.AddressFamily == AddressFamily.InterNetwork) |
|
294 |
{ |
|
295 |
return ip.ToString(); |
|
296 |
} |
|
297 |
} |
|
298 |
throw new Exception("No network adapters with an IPv4 address in the system!"); |
|
299 |
} |
|
300 |
|
|
301 |
} |
|
302 |
|
|
303 |
|
|
304 |
|
|
305 |
|
|
306 |
|
|
307 |
|
|
308 |
|
|
309 |
|
|
310 |
|
|
311 |
|
|
312 |
|
|
313 |
|
|
314 |
|
|
315 |
|
|
316 |
|
|
317 |
|
|
318 |
|
|
319 |
|
|
320 |
// --------------------------------------------------------------------------- |
|
321 |
|
|
322 |
|
|
323 |
|
|
324 |
|
|
325 |
|
|
326 |
|
|
327 |
|
|
328 |
|
|
329 |
class ClientService |
|
330 |
{ |
|
331 |
public static readonly int MAX_IDS = 1000000; // ?? |
|
332 |
public static int IDs = 0; |
|
333 |
public int UniqueID; |
|
334 |
public Request ClientRequest; |
|
335 |
public Response ClientResponse; |
|
336 |
} |
|
337 |
|
|
338 |
public class ConnectionListenerMulti |
|
339 |
{ |
|
340 |
private readonly int PORT; |
|
341 |
private ConcurrentDictionary<int, ClientService> readyRequests; |
|
342 |
private ConcurrentQueue<ClientService> waitingRequests; |
|
343 |
|
|
344 |
|
|
345 |
public ConnectionListenerMulti(int port) |
|
346 |
{ |
|
347 |
this.PORT = port; |
|
348 |
} |
|
349 |
|
|
350 |
|
|
351 |
private void RequestHandler() |
|
352 |
{ |
|
353 |
while (true) |
|
354 |
{ |
|
355 |
if (!waitingRequests.IsEmpty) |
|
356 |
{ |
|
357 |
Console.WriteLine("handling a request for 10s..."); |
|
358 |
ClientService nextService; |
|
359 |
bool deqResultOk = waitingRequests.TryDequeue(out nextService); |
|
360 |
// nextService has ID and request filled out |
|
361 |
Thread.Sleep(10000); |
|
362 |
|
|
363 |
Console.WriteLine("finished building response, adding it to the dictionary..."); |
|
364 |
//ClientService service = new ClientService(); |
|
365 |
//service.UniqueID = GetNextID(); |
|
366 |
//service.ClientRequest = Request.Randomize(); |
|
367 |
nextService.ClientResponse = Response.Randomize(); |
|
368 |
bool resultOk = readyRequests.TryAdd(nextService.UniqueID, nextService); |
|
369 |
if (!resultOk) |
|
370 |
{ |
|
371 |
Console.WriteLine("ID " + nextService.UniqueID + " is being used!"); |
|
372 |
// do nothing? - keep it in the queue and let the client try later perhaps? |
|
373 |
} |
|
374 |
else |
|
375 |
{ |
|
376 |
// added to dictionary |
|
377 |
// -> remove it from the queue |
|
378 |
|
|
379 |
} |
|
380 |
} |
|
381 |
else |
|
382 |
{ |
|
383 |
Thread.Sleep(100); // ?? |
|
384 |
} |
|
385 |
|
|
386 |
} |
|
387 |
|
|
388 |
|
|
389 |
} |
|
390 |
|
|
391 |
private int GetNextID() |
|
392 |
{ |
|
393 |
int id = (ClientService.IDs++) % ClientService.MAX_IDS; // we presume that after a million requests, the first ids are free again, if not, tough luck |
|
394 |
return id; |
|
395 |
} |
|
396 |
|
|
397 |
public void StartListening() |
|
398 |
{ |
|
399 |
string ip = GetLocalIPAddress(); |
|
400 |
Console.WriteLine("ip : " + ip); |
|
401 |
HttpListener server = new HttpListener(); |
|
402 |
//server.Prefixes.Add($"https://{ip}:{PORT}/"); |
|
403 |
server.Prefixes.Add($"http://localhost:{PORT}/"); |
|
404 |
|
|
405 |
server.Start(); |
|
406 |
|
|
407 |
Console.WriteLine("Listening..."); |
|
408 |
|
|
409 |
waitingRequests = new ConcurrentQueue<ClientService>(); |
|
410 |
readyRequests = new ConcurrentDictionary<int, ClientService>(); |
|
411 |
|
|
412 |
|
|
413 |
Thread requestHandlerThread = new Thread(RequestHandler); |
|
414 |
requestHandlerThread.Start(); |
|
415 |
|
|
416 |
while (true) |
|
417 |
{ |
|
418 |
Console.WriteLine("Waiting for a client request..."); |
|
419 |
//Console.ReadLine(); |
|
420 |
|
|
421 |
HttpListenerContext context = server.GetContext(); |
|
422 |
//Thread.Sleep(10000); |
|
423 |
|
|
424 |
//IAsyncResult result = server.BeginGetContext(new AsyncCallback(ListenerCallback), server); |
|
425 |
//Console.WriteLine("Waiting for request to be processed asyncronously."); |
|
426 |
//result.AsyncWaitHandle.WaitOne(); |
|
427 |
//Console.WriteLine("Request processed asyncronously."); |
|
428 |
|
|
429 |
|
|
430 |
|
|
431 |
if (context.Request.HttpMethod == "GET") // when client says download |
|
432 |
{ |
|
433 |
Console.WriteLine("received GET request"); |
|
434 |
|
|
435 |
HttpListenerResponse response = context.Response; |
|
436 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
437 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
438 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
439 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
440 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
441 |
|
|
442 |
|
|
443 |
|
|
444 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; |
|
445 |
// if (page == string.Empty) |
|
446 |
// page = "test.txt"; |
|
447 |
// |
|
448 |
// TextReader tr = new StreamReader(page); |
|
449 |
// string msg = tr.ReadToEnd(); |
|
450 |
|
|
451 |
int rand = new Random().Next(1, 10); |
|
452 |
string msg = "This is a response from the server :) " + rand; |
|
453 |
|
|
454 |
Response xmlResp = Response.Randomize(); |
|
455 |
var xml = XmlCommunication.Serialize(xmlResp); |
|
456 |
//Console.WriteLine(xml); |
|
457 |
|
|
458 |
msg = xml; |
|
459 |
|
|
460 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
461 |
|
|
462 |
response.ContentLength64 = buffer.Length; |
|
463 |
Stream st = response.OutputStream; |
|
464 |
st.Write(buffer, 0, buffer.Length); |
|
465 |
|
|
466 |
|
|
467 |
context.Response.Close(); |
|
468 |
} |
|
469 |
|
|
470 |
else if (context.Request.HttpMethod == "POST") // when client says upload |
|
471 |
{ |
|
472 |
Console.WriteLine("received POST request"); |
|
473 |
|
|
474 |
string text; |
|
475 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) |
|
476 |
text = reader.ReadToEnd(); |
|
477 |
Console.WriteLine("Received request:"); |
|
478 |
string requestXML = HttpUtility.UrlDecode(text); |
|
479 |
Console.WriteLine(requestXML); |
|
480 |
|
|
481 |
Request newRequest = new Request(); |
|
482 |
Request requestDeserialized = XmlCommunication.Deserialize(newRequest, requestXML); |
|
483 |
|
|
484 |
ClientService newService = new ClientService(); |
|
485 |
newService.UniqueID = GetNextID(); |
|
486 |
newService.ClientRequest = requestDeserialized; |
|
487 |
// save the request to the queue |
|
488 |
waitingRequests.Enqueue(newService); |
|
489 |
|
|
490 |
|
|
491 |
|
|
492 |
// SEND THE ID: - TODO xml format also |
|
493 |
HttpListenerResponse response = context.Response; |
|
494 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
495 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
496 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
497 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
498 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
499 |
|
|
500 |
|
|
501 |
|
|
502 |
int rand = new Random().Next(1, 10); |
|
503 |
string msg = "" + newService.UniqueID; |
|
504 |
|
|
505 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
506 |
|
|
507 |
response.ContentLength64 = buffer.Length; |
|
508 |
Stream st = response.OutputStream; |
|
509 |
st.Write(buffer, 0, buffer.Length); |
|
510 |
|
|
511 |
|
|
512 |
context.Response.Close(); // ?? Works better with this, if this line is absent, the client gets 'stuck' after approximately 6 messages |
|
513 |
} |
|
514 |
else |
|
515 |
{ |
|
516 |
Console.WriteLine("received request other than GET or POST"); |
|
517 |
Console.WriteLine("method: " + context.Request.HttpMethod); |
|
518 |
Console.WriteLine("headers: " + context.Request.Headers); |
|
519 |
Console.WriteLine("whole request?: " + context.Request); |
|
520 |
Console.WriteLine("user: " + context.User); |
|
521 |
|
|
522 |
|
|
523 |
|
|
524 |
//HttpListenerResponse response = context.Response; |
|
525 |
//response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
526 |
//response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
527 |
//response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time, Origin, Content-Type, X-Auth-Token"); |
|
528 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
529 |
//response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
530 |
|
|
531 |
//string msg = "Preflight check? "; |
|
532 |
|
|
533 |
//byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
534 |
|
|
535 |
//response.ContentLength64 = buffer.Length; |
|
536 |
//Stream st = response.OutputStream; |
|
537 |
//st.Write(buffer, 0, buffer.Length); |
|
538 |
|
|
539 |
|
|
540 |
//context.Response.Close(); // ?? |
|
541 |
|
|
542 |
} |
|
543 |
} |
|
544 |
} |
|
545 |
|
|
546 |
|
|
547 |
|
|
548 |
|
|
549 |
|
|
550 |
|
|
551 |
|
|
552 |
|
|
553 |
|
|
554 |
|
|
555 |
|
|
556 |
private void ListenerCallback(IAsyncResult result) |
|
557 |
{ |
|
558 |
HttpListener listener = (HttpListener)result.AsyncState; |
|
559 |
// Call EndGetContext to complete the asynchronous operation. |
|
560 |
HttpListenerContext context = listener.EndGetContext(result); |
|
561 |
|
|
562 |
Console.WriteLine("callbacking..."); |
|
563 |
|
|
564 |
Thread.Sleep(10000); |
|
565 |
|
|
566 |
if (context.Request.HttpMethod == "GET") // when client says download |
|
567 |
{ |
|
568 |
Console.WriteLine("received GET request"); |
|
569 |
|
|
570 |
HttpListenerResponse response = context.Response; |
|
571 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
572 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
573 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
574 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
575 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
576 |
|
|
577 |
|
|
578 |
|
|
579 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; |
|
580 |
// if (page == string.Empty) |
|
581 |
// page = "test.txt"; |
|
582 |
// |
|
583 |
// TextReader tr = new StreamReader(page); |
|
584 |
// string msg = tr.ReadToEnd(); |
|
585 |
|
|
586 |
int rand = new Random().Next(1, 10); |
|
587 |
string msg = "This is a response from the server :) " + rand; |
|
588 |
|
|
589 |
Response xmlResp = Response.Randomize(); |
|
590 |
var xml = XmlCommunication.Serialize(xmlResp); |
|
591 |
//Console.WriteLine(xml); |
|
592 |
|
|
593 |
msg = xml; |
|
594 |
|
|
595 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
596 |
|
|
597 |
response.ContentLength64 = buffer.Length; |
|
598 |
Stream st = response.OutputStream; |
|
599 |
st.Write(buffer, 0, buffer.Length); |
|
600 |
|
|
601 |
|
|
602 |
context.Response.Close(); |
|
603 |
} |
|
604 |
|
|
605 |
else if (context.Request.HttpMethod == "POST") // when client says upload |
|
606 |
{ |
|
607 |
Console.WriteLine("received POST request"); |
|
608 |
|
|
609 |
string text; |
|
610 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) |
|
611 |
text = reader.ReadToEnd(); |
|
612 |
Console.WriteLine("Received request:"); |
|
613 |
Console.WriteLine(HttpUtility.UrlDecode(text)); |
|
614 |
|
|
615 |
|
|
616 |
|
|
617 |
HttpListenerResponse response = context.Response; |
|
618 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
619 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
620 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
621 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
622 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
623 |
|
|
624 |
|
|
625 |
|
|
626 |
int rand = new Random().Next(1, 10); |
|
627 |
string msg = "OK " + rand; |
|
628 |
|
|
629 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
630 |
|
|
631 |
response.ContentLength64 = buffer.Length; |
|
632 |
Stream st = response.OutputStream; |
|
633 |
st.Write(buffer, 0, buffer.Length); |
|
634 |
|
|
635 |
|
|
636 |
context.Response.Close(); // ?? Works better with this, if this line is absent, the client gets 'stuck' after approximately 6 messages |
|
637 |
} |
|
638 |
else |
|
639 |
{ |
|
640 |
Console.WriteLine("received request other than GET or POST"); |
|
641 |
Console.WriteLine("method: " + context.Request.HttpMethod); |
|
642 |
Console.WriteLine("headers: " + context.Request.Headers); |
|
643 |
Console.WriteLine("whole request?: " + context.Request); |
|
644 |
Console.WriteLine("user: " + context.User); |
|
645 |
|
|
646 |
|
|
647 |
|
|
648 |
//HttpListenerResponse response = context.Response; |
|
649 |
//response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
650 |
//response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
651 |
//response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time, Origin, Content-Type, X-Auth-Token"); |
|
652 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
653 |
//response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
654 |
|
|
655 |
//string msg = "Preflight check? "; |
|
656 |
|
|
657 |
//byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
658 |
|
|
659 |
//response.ContentLength64 = buffer.Length; |
|
660 |
//Stream st = response.OutputStream; |
|
661 |
//st.Write(buffer, 0, buffer.Length); |
|
662 |
|
|
663 |
|
|
664 |
//context.Response.Close(); // ?? |
|
665 |
|
|
666 |
} |
|
667 |
|
|
668 |
|
|
669 |
|
|
670 |
|
|
671 |
|
|
672 |
|
|
673 |
|
|
674 |
|
|
675 |
|
|
676 |
|
|
677 |
//HttpListenerRequest request = context.Request; |
|
678 |
//// Obtain a response object. |
|
679 |
//HttpListenerResponse response = context.Response; |
|
680 |
//// Construct a response. |
|
681 |
//string responseString = "<HTML><BODY> Hello world!</BODY></HTML>"; |
|
682 |
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); |
|
683 |
//// Get a response stream and write the response to it. |
|
684 |
//response.ContentLength64 = buffer.Length; |
|
685 |
//System.IO.Stream output = response.OutputStream; |
|
686 |
//output.Write(buffer, 0, buffer.Length); |
|
687 |
//// You must close the output stream. |
|
688 |
//output.Close(); |
|
689 |
} |
|
690 |
|
|
691 |
|
|
692 |
private string GetLocalIPAddress() |
|
693 |
{ |
|
694 |
var host = Dns.GetHostEntry(Dns.GetHostName()); |
|
695 |
foreach (var ip in host.AddressList) |
|
696 |
{ |
|
697 |
if (ip.AddressFamily == AddressFamily.InterNetwork) |
|
698 |
{ |
|
699 |
return ip.ToString(); |
|
700 |
} |
|
701 |
} |
|
702 |
throw new Exception("No network adapters with an IPv4 address in the system!"); |
|
703 |
} |
|
704 |
|
|
705 |
} |
|
706 |
|
|
707 |
} |
Server/ServerApp/DataDownload/Date.cs | ||
---|---|---|
117 | 117 |
return !(d1 > d2); |
118 | 118 |
} |
119 | 119 |
|
120 |
public static bool operator ==(Date d1, Date d2) |
|
121 |
{ |
|
122 |
return d1.Equals(d2); |
|
123 |
} |
|
124 |
|
|
125 |
public static bool operator !=(Date d1, Date d2) |
|
126 |
{ |
|
127 |
return !d1.Equals(d2); |
|
128 |
} |
|
120 |
//public static bool operator ==(Date d1, Date d2)
|
|
121 |
//{
|
|
122 |
// return d1.Equals(d2);
|
|
123 |
//}
|
|
124 |
|
|
125 |
//public static bool operator !=(Date d1, Date d2)
|
|
126 |
//{
|
|
127 |
// return !d1.Equals(d2);
|
|
128 |
//}
|
|
129 | 129 |
|
130 | 130 |
#endregion |
131 | 131 |
} |
Server/ServerApp/Program.cs | ||
---|---|---|
42 | 42 |
return; |
43 | 43 |
} |
44 | 44 |
|
45 |
|
|
45 |
// commands accepting test |
|
46 | 46 |
//create a thread for commands accepting: |
47 | 47 |
//Thread inputThread = new Thread(CommandsAcceptor.AcceptCommand); |
48 | 48 |
//inputThread.Start(); |
49 | 49 |
|
50 | 50 |
|
51 |
|
|
51 |
// is this obsolete? |
|
52 | 52 |
//DataParser p = new DataParser("data/"); |
53 | 53 |
//p.Parse(); |
54 | 54 |
|
55 |
#region UNCOMMENT |
|
55 |
|
|
56 |
|
|
57 |
// data download test |
|
58 |
//DataDownloader dd = DataDownloadAndRetrievalTest(config); |
|
59 |
|
|
60 |
// xml building test |
|
61 |
//XMLTest(); |
|
62 |
|
|
63 |
|
|
64 |
|
|
65 |
// PARSE DATA |
|
66 |
|
|
67 |
|
|
68 |
|
|
69 |
|
|
70 |
// json parser test |
|
71 |
//JSONParserTest(); |
|
72 |
|
|
73 |
// model test |
|
74 |
//IPredictionController controller = PredictionTest(dd); |
|
75 |
|
|
76 |
|
|
77 |
|
|
78 |
//parse(new DateTime(2019, 10, 5), , interval = 1, wholeDay = true) |
|
79 |
|
|
80 |
|
|
81 |
// connection test |
|
82 |
ConnectionTest(/*controller,*/ config); |
|
83 |
|
|
84 |
|
|
85 |
Console.ReadLine(); |
|
86 |
} |
|
87 |
|
|
88 |
|
|
89 |
private static DataDownloader DataDownloadAndRetrievalTest(Config config) |
|
90 |
{ |
|
56 | 91 |
//test scenario -data download: |
57 | 92 |
DataDownloader dd = new DataDownloader(config.DataRootDir, config.DataWebsite, config.DownloadedFilesNaming); |
58 | 93 |
dd.OverwriteExisting = false; |
... | ... | |
63 | 98 |
|
64 | 99 |
|
65 | 100 |
|
66 |
//Console.WriteLine("Saved files: "); |
|
67 |
//foreach (string s in savedFiles) |
|
68 |
//{ |
|
69 |
// Console.WriteLine(s); |
|
70 |
//} |
|
71 |
|
|
72 |
//Console.WriteLine("subdirectories: "); |
|
73 |
//foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories) |
|
74 |
//{ |
|
75 |
// Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); |
|
76 |
//} |
|
77 |
|
|
78 |
//List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new DataDownload.Date(10, 2019), new DataDownload.Date(12, 2020)); |
|
79 |
//Console.WriteLine("Retrieved data: "); |
|
80 |
//foreach (string s in retrievedData) |
|
81 |
//{ |
|
82 |
// Console.WriteLine(s); |
|
83 |
//} |
|
84 |
//Console.WriteLine("all from directory:"); |
|
85 |
//retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], null, null); |
|
86 |
//foreach (string s in retrievedData) |
|
87 |
//{ |
|
88 |
// Console.WriteLine(s); |
|
89 |
//} |
|
90 |
// test - connection: |
|
91 |
//ConnectionListener cl = new ConnectionListener(int.Parse(config.Port)); |
|
92 |
//cl.StartListening(); |
|
93 |
#endregion |
|
94 |
|
|
95 |
#region XML_TEST |
|
96 |
//Response response = Response.Randomize(); |
|
97 |
//var xml = XmlCommunication.Serialize(response); |
|
98 |
//Console.WriteLine(xml); |
|
99 |
//Response responseDeserialized = XmlCommunication.Deserialize(response, xml); |
|
100 |
|
|
101 |
//Console.WriteLine("------"); |
|
102 |
|
|
103 |
|
|
104 |
//Request request = Request.Randomize(); |
|
105 |
//xml = XmlCommunication.Serialize(request); |
|
106 |
//Console.WriteLine(xml); |
|
107 |
//Request requestDeserialized = XmlCommunication.Deserialize(request, xml); |
|
108 |
#endregion |
|
109 |
|
|
110 |
|
|
111 |
//Console.WriteLine("Saved files: "); |
|
112 |
//foreach (string s in savedFiles) |
|
113 |
//{ |
|
114 |
// Console.WriteLine(s); |
|
115 |
//} |
|
116 |
|
|
117 |
//Console.WriteLine("subdirectories: "); |
|
118 |
//foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories) |
|
119 |
//{ |
|
120 |
// Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); |
|
121 |
//} |
|
122 |
|
|
123 |
/* |
|
124 |
|
|
125 |
List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new Date(10, 2019), new Date(12, 2020)); |
|
101 |
Console.WriteLine("Saved files: "); |
|
102 |
foreach (string s in savedFiles) |
|
103 |
{ |
|
104 |
Console.WriteLine(s); |
|
105 |
} |
|
106 |
|
|
107 |
Console.WriteLine("subdirectories: "); |
|
108 |
foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories) |
|
109 |
{ |
|
110 |
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); |
|
111 |
} |
|
112 |
|
|
113 |
List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new DataDownload.Date(10, 2019), new DataDownload.Date(12, 2020)); |
|
126 | 114 |
Console.WriteLine("Retrieved data: "); |
127 | 115 |
foreach (string s in retrievedData) |
128 | 116 |
{ |
129 | 117 |
Console.WriteLine(s); |
130 | 118 |
} |
131 |
*/ |
|
119 |
Console.WriteLine("all from directory:"); |
|
120 |
retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], null, null); |
|
121 |
foreach (string s in retrievedData) |
|
122 |
{ |
|
123 |
Console.WriteLine(s); |
|
124 |
} |
|
125 |
|
|
126 |
|
|
127 |
return dd; |
|
128 |
} |
|
129 |
|
|
130 |
|
|
131 |
private static void XMLTest() |
|
132 |
{ |
|
133 |
Response response = Response.Randomize(); |
|
134 |
var xml = XmlCommunication.Serialize(response); |
|
135 |
Console.WriteLine(xml); |
|
136 |
Response responseDeserialized = XmlCommunication.Deserialize(response, xml); |
|
132 | 137 |
|
133 |
// PARSE DATA
|
|
138 |
Console.WriteLine("------");
|
|
134 | 139 |
|
135 | 140 |
|
141 |
Request request = Request.Randomize(); |
|
142 |
xml = XmlCommunication.Serialize(request); |
|
143 |
Console.WriteLine(xml); |
|
144 |
Request requestDeserialized = XmlCommunication.Deserialize(request, xml); |
|
145 |
} |
|
146 |
|
|
136 | 147 |
|
137 |
JsonParser jsonP = new JsonParser(null); |
|
148 |
private static void JSONParserTest() |
|
149 |
{ |
|
150 |
JsonParser jsonP = new JsonParser(null); |
|
138 | 151 |
jsonP.ParsePrediction(); |
139 | 152 |
|
140 | 153 |
var res = jsonP.GetPredictionForTime(jsonP.Predictions[5].startTime, jsonP.Predictions[20].startTime); |
... | ... | |
142 | 155 |
Console.WriteLine("end " + jsonP.Predictions[20].startTime); |
143 | 156 |
foreach (WeatherInfo w in res) |
144 | 157 |
Console.WriteLine(w.ToString()); |
158 |
} |
|
145 | 159 |
|
146 |
|
|
160 |
private static IPredictionController PredictionTest(DataDownloader dd) |
|
161 |
{ |
|
147 | 162 |
// TODO nastavit čas |
148 | 163 |
IDataParser p = new DataParser(dd); |
149 |
IPredictionController predictionController = new PredictionController(p); |
|
150 |
predictionController.Train(); |
|
151 |
//var results = predictionController.Predict() |
|
152 |
|
|
153 |
|
|
154 |
//parse(new DateTime(2019, 10, 5), , interval = 1, wholeDay = true) |
|
164 |
IPredictionController predictionController = new PredictionController(p); |
|
165 |
predictionController.Train(); |
|
166 |
//var results = predictionController.Predict() |
|
155 | 167 |
|
168 |
return predictionController; |
|
169 |
} |
|
156 | 170 |
|
157 |
// test - connection: |
|
158 |
//ConnectionListener cl = new ConnectionListener(int.Parse(args[0])/*8000*//*int.Parse(config.Port)*/); |
|
159 |
//cl.StartListening(); |
|
171 |
private static void ConnectionTest(/*IPredictionController predictionController,*/ Config config) |
|
172 |
{ |
|
173 |
ConnectionListener cl = new ConnectionListener(int.Parse(config.Port)); |
|
174 |
cl.StartListening(); |
|
160 | 175 |
|
161 |
Console.ReadLine(); |
|
162 |
} |
|
176 |
//HttpRequestHandler hrh = new HttpRequestHandler(int.Parse(config.Port)); |
|
177 |
//hrh.ListenAsynchronously(); |
|
178 |
} |
|
163 | 179 |
|
164 | 180 |
|
165 |
private static Config FillConfigInfo(string[] args)
|
|
181 |
private static Config FillConfigInfo(string[] args)
|
|
166 | 182 |
{ |
167 | 183 |
|
168 | 184 |
Config extractedConfigInfo = new Config(); |
Server/ServerApp/ServerApp.csproj | ||
---|---|---|
157 | 157 |
<Reference Include="System.Xml" /> |
158 | 158 |
</ItemGroup> |
159 | 159 |
<ItemGroup> |
160 |
<Compile Include="Connection\ConnectionListener.cs" /> |
|
160 |
<Compile Include="Connection\ConnectionListenerMulti.cs" />
|
|
161 | 161 |
<Compile Include="Connection\XMLProtocolHandler\Buildings.cs" /> |
162 | 162 |
<Compile Include="Connection\XMLProtocolHandler\Date.cs" /> |
163 | 163 |
<Compile Include="Connection\XMLProtocolHandler\Prediction.cs" /> |
Také k dispozici: Unified diff
Re #8941. Started working on enqueueing requests and processing them in a new thread. + Program.cs cleanup + Fixed Date error.