Revize 3aba3c34
Přidáno uživatelem Eliška Mourycová před téměř 4 roky(ů)
Server/ServerApp/Connection/ConnectionListener.cs | ||
---|---|---|
1 |
// |
|
2 |
// Author: Eliska Mourycova |
|
3 |
// |
|
4 |
|
|
5 |
using System; |
|
6 |
using System.IO; |
|
7 |
using System.Net; |
|
8 |
using System.Net.Sockets; |
|
9 |
using System.Text; |
|
10 |
using System.Threading; |
|
11 |
using System.Web; |
|
12 |
|
|
13 |
namespace ServerApp.Connection |
|
14 |
{ |
|
15 |
// /// <summary> |
|
16 |
// /// State object for reading client data asynchronously |
|
17 |
// /// </summary> |
|
18 |
// public class StateObject |
|
19 |
// { |
|
20 |
// // Client socket. |
|
21 |
// public Socket WorkSocket = null; |
|
22 |
// // Size of receive buffer. |
|
23 |
// public const int BUFFER_SIZE = 1024; |
|
24 |
// // Receive buffer. |
|
25 |
// public byte[] Buffer = new byte[BUFFER_SIZE]; |
|
26 |
// // Received data string. |
|
27 |
// public StringBuilder StrBuilder = new StringBuilder(); |
|
28 |
// } |
|
29 |
|
|
30 |
// /// <summary> |
|
31 |
// /// This class takes care of client connection. It serves clients asynchronously. |
|
32 |
// /// </summary> |
|
33 |
// public class AsynchronousSocketListener |
|
34 |
// { |
|
35 |
// // port numbers: |
|
36 |
// private const int PORT_NO = 11000; |
|
37 |
// private const int ADMIN_PORT_NO = 10000; |
|
38 |
|
|
39 |
|
|
40 |
// // Thread signal |
|
41 |
// private ManualResetEvent allDone = new ManualResetEvent(false); |
|
42 |
|
|
43 |
// /// <summary> |
|
44 |
// /// Starts listening and accepting connections. It serves requests when they come. |
|
45 |
// /// </summary> |
|
46 |
// public void StartListening() |
|
47 |
// { |
|
48 |
// // Data buffer for incoming data. |
|
49 |
// byte[] bytes = new Byte[1024]; |
|
50 |
|
|
51 |
// // Establish the local endpoint for the socket: |
|
52 |
// IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); |
|
53 |
|
|
54 |
// // Get the IP of the machine - UNUSED ATM, USING LOOPBACK ON LOCALHOST |
|
55 |
// IPAddress ipAddress = ipHostInfo.AddressList[1]; |
|
56 |
// Console.WriteLine("machine ip: " + ipAddress.ToString()); |
|
57 |
// IPEndPoint localEndPoint = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, PORT_NO); |
|
58 |
// IPEndPoint localEndPointAdmin = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, ADMIN_PORT_NO); |
|
59 |
|
|
60 |
// // Create a TCP/IP socket. |
|
61 |
// Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
|
62 |
// Socket listenerAdmin = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
|
63 |
|
|
64 |
// // Bind the socket to the local endpoint and listen for incoming connections. |
|
65 |
// try |
|
66 |
// { |
|
67 |
// listener.Bind(localEndPoint); |
|
68 |
// listener.Listen(100); |
|
69 |
|
|
70 |
// listenerAdmin.Bind(localEndPointAdmin); |
|
71 |
// listenerAdmin.Listen(1); |
|
72 |
|
|
73 |
// // keep accepting |
|
74 |
// while (true) |
|
75 |
// { |
|
76 |
// // Set the event to nonsignaled state. |
|
77 |
// allDone.Reset(); |
|
78 |
|
|
79 |
// // Start an asynchronous socket to listen for connections. |
|
80 |
// Console.WriteLine("Waiting for a connection..."); |
|
81 |
// listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); |
|
82 |
// listenerAdmin.BeginAccept(new AsyncCallback(AcceptCallback), listenerAdmin); |
|
83 |
|
|
84 |
// // Wait until a connection is made before continuing. |
|
85 |
// allDone.WaitOne(); |
|
86 |
// } |
|
87 |
|
|
88 |
// } |
|
89 |
// catch (Exception e) |
|
90 |
// { |
|
91 |
// // bind failed |
|
92 |
// Console.WriteLine(e.ToString()); |
|
93 |
// } |
|
94 |
|
|
95 |
// Console.WriteLine("\nPress ENTER to continue..."); |
|
96 |
// Console.Read(); |
|
97 |
|
|
98 |
// } |
|
99 |
|
|
100 |
// // Routine for when BeginAccept on the given listener ended |
|
101 |
// private void AcceptCallback(IAsyncResult ar) |
|
102 |
// { |
|
103 |
// // Signal the main thread to continue. |
|
104 |
// allDone.Set(); |
|
105 |
// Console.WriteLine("Accepted a connection."); |
|
106 |
|
|
107 |
|
|
108 |
// // Get the socket that handles the client request. |
|
109 |
// Socket listener = (Socket)ar.AsyncState; |
|
110 |
// Socket handler = listener.EndAccept(ar); |
|
111 |
|
|
112 |
// // debug |
|
113 |
// Console.WriteLine("handler: "); |
|
114 |
// Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)handler.RemoteEndPoint).Address.ToString()) + " on port number " + ((IPEndPoint)handler.RemoteEndPoint).Port.ToString()); |
|
115 |
// Console.WriteLine("My local IpAddress is : " + IPAddress.Parse(((IPEndPoint)handler.LocalEndPoint).Address.ToString()) + ". I am connected on port number " + ((IPEndPoint)handler.LocalEndPoint).Port.ToString()); |
|
116 |
|
|
117 |
|
|
118 |
|
|
119 |
|
|
120 |
// // Create the state object. |
|
121 |
// StateObject state = new StateObject(); |
|
122 |
// state.WorkSocket = handler; |
|
123 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
124 |
|
|
125 |
// } |
|
126 |
|
|
127 |
// // Routine for when BeginReceive on the given listener ended |
|
128 |
// private void ReadCallback(IAsyncResult ar) |
|
129 |
// { |
|
130 |
// // string for the received message |
|
131 |
// String content = String.Empty; |
|
132 |
|
|
133 |
// // Retrieve the state object and the handler socket |
|
134 |
// // from the asynchronous state object. |
|
135 |
// StateObject state = (StateObject)ar.AsyncState; |
|
136 |
// Socket handler = state.WorkSocket; |
|
137 |
|
|
138 |
// // check if we're still connected |
|
139 |
// if (!SocketConnected(handler)) |
|
140 |
// { |
|
141 |
// // if the client isn't connected anymore, take care of cleanup |
|
142 |
// Console.WriteLine("Closing connection - unexpected..."); |
|
143 |
// CloseConnection(handler); |
|
144 |
|
|
145 |
// // return so that we don't attempt to read from a non-existent stream |
|
146 |
// return; |
|
147 |
// } |
|
148 |
|
|
149 |
// // check if it is admin's request we're serving |
|
150 |
// bool admin = ((IPEndPoint)handler.LocalEndPoint).Port == ADMIN_PORT_NO; |
|
151 |
|
|
152 |
// // Read data from the client socket. |
|
153 |
// int bytesRead = handler.EndReceive(ar); |
|
154 |
|
|
155 |
// if (bytesRead > 0) |
|
156 |
// { |
|
157 |
// // There might be more data, so store the data received so far. |
|
158 |
// state.StrBuilder.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead)); |
|
159 |
|
|
160 |
// // Check for end-of-file tag. If it is not there, read more data. |
|
161 |
// content = state.StrBuilder.ToString(); |
|
162 |
// if (content.IndexOf("!") > -1) |
|
163 |
// { |
|
164 |
// // All the data has been read from the client. Display it on the console. |
|
165 |
// Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); |
|
166 |
|
|
167 |
// // parse the message and determine the response: |
|
168 |
// content = ParseMessageAndBuildAnswer(content, admin); |
|
169 |
|
|
170 |
// // check if the client wishes to close the connection: |
|
171 |
// if (content.Equals("bye!")) |
|
172 |
// { |
|
173 |
// Console.WriteLine("Closing connection - expected..."); |
|
174 |
// //handler.Shutdown(SocketShutdown.Both); |
|
175 |
// //handler.Close(); |
|
176 |
// CloseConnection(handler); |
|
177 |
// return; |
|
178 |
// } |
|
179 |
|
|
180 |
// // Send a response to the client |
|
181 |
// Send(handler, content); |
|
182 |
|
|
183 |
// // clear the string |
|
184 |
// state.StrBuilder.Clear(); |
|
185 |
|
|
186 |
// // begin receiving another message: |
|
187 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
188 |
// } |
|
189 |
// else |
|
190 |
// { |
|
191 |
// // Not all data received. Get more. |
|
192 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
193 |
// } |
|
194 |
// } |
|
195 |
// } |
|
196 |
|
|
197 |
// // Takes care of sending data to a connected client |
|
198 |
// private void Send(Socket handler, String data) |
|
199 |
// { |
|
200 |
// // Convert the string data to byte data using ASCII encoding. |
|
201 |
// byte[] byteData = Encoding.ASCII.GetBytes(data); |
|
202 |
|
|
203 |
// // Begin sending the data to the remote device. |
|
204 |
// handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); |
|
205 |
// } |
|
206 |
|
|
207 |
// // Routine for when BeginSend on the given listener ended |
|
208 |
// private void SendCallback(IAsyncResult ar) |
|
209 |
// { |
|
210 |
// try |
|
211 |
// { |
|
212 |
// // Retrieve the socket from the state object. |
|
213 |
// Socket handler = (Socket)ar.AsyncState; |
|
214 |
|
|
215 |
// // Complete sending the data to the remote device. |
|
216 |
// int bytesSent = handler.EndSend(ar); |
|
217 |
// Console.WriteLine("Sent {0} bytes to client.", bytesSent); |
|
218 |
|
|
219 |
|
|
220 |
// //handler.Shutdown(SocketShutdown.Both); |
|
221 |
// //handler.Close(); |
|
222 |
|
|
223 |
// } |
|
224 |
// catch (Exception e) |
|
225 |
// { |
|
226 |
// // close connection here? |
|
227 |
|
|
228 |
// Console.WriteLine(e.ToString()); |
|
229 |
// } |
|
230 |
// } |
|
231 |
|
|
232 |
|
|
233 |
// /// <summary> |
|
234 |
// /// Parses the incoming request and determines the response. |
|
235 |
// /// </summary> |
|
236 |
// /// <param name="message">The incoming message from the client</param> |
|
237 |
// /// <param name="admin">A flag saying whether it is admin's request</param> |
|
238 |
// /// <returns></returns> |
|
239 |
// private string ParseMessageAndBuildAnswer(string message, bool admin) |
|
240 |
//{ |
|
241 |
// Console.WriteLine("Parsing message from admin: " + admin); |
|
242 |
// string ans = ""; |
|
243 |
|
|
244 |
// if (message.Equals("hello!")) |
|
245 |
// { |
|
246 |
// ans = "hello to you too."; |
|
247 |
// } |
|
248 |
// else if (message.Equals("weather!")) |
|
249 |
// { |
|
250 |
// ans = "weather will be nice"; |
|
251 |
// } |
|
252 |
// else if (message.Equals("bye!")) |
|
253 |
// { |
|
254 |
// ans = "bye!"; |
|
255 |
// } |
|
256 |
// else |
|
257 |
// { |
|
258 |
// // here bye too, if we want to disconnect clients who don't follow protocol |
|
259 |
// ans = "bye!";//"i didnt understand that"; |
|
260 |
|
|
261 |
// } |
|
262 |
|
|
263 |
// return ans; |
|
264 |
//} |
|
265 |
|
|
266 |
// /// <summary> |
|
267 |
// /// Closes the connection on the passed Socket |
|
268 |
// /// </summary> |
|
269 |
// /// <param name="s">The socket to close the connection for</param> |
|
270 |
// private void CloseConnection(Socket s) |
|
271 |
//{ |
|
272 |
// s.Shutdown(SocketShutdown.Both); |
|
273 |
// s.Close(); |
|
274 |
// } |
|
275 |
|
|
276 |
// /// <summary> |
|
277 |
// /// Checks whether the connection on a given socket is active |
|
278 |
// /// </summary> |
|
279 |
// /// <param name="s">The socket to check for connection activity</param> |
|
280 |
// /// <returns>True if the connection is active, false otherwise</returns> |
|
281 |
// private bool SocketConnected(Socket s) |
|
282 |
// { |
|
283 |
// bool part1 = s.Poll(1000, SelectMode.SelectRead); |
|
284 |
// bool part2 = (s.Available == 0); |
|
285 |
// if (part1 && part2) |
|
286 |
// return false; |
|
287 |
// else |
|
288 |
// return true; |
|
289 |
// } |
|
290 |
// } |
|
291 |
|
|
292 |
|
|
293 |
public class ConnectionListener |
|
294 |
{ |
|
295 |
private readonly int PORT; |
|
296 |
|
|
297 |
public ConnectionListener(int port) |
|
298 |
{ |
|
299 |
this.PORT = port; |
|
300 |
} |
|
301 |
|
|
302 |
public void StartListening() |
|
303 |
{ |
|
304 |
string ip = GetLocalIPAddress(); |
|
305 |
Console.WriteLine("ip : " + ip); |
|
306 |
HttpListener server = new HttpListener(); |
|
307 |
server.Prefixes.Add($"http://*:{PORT}/work/"); |
|
308 |
server.Prefixes.Add($"https://*:{PORT}/work2/"); |
|
309 |
//server.Prefixes.Add($"http://localhost:{PORT}/work/"); |
|
310 |
//server.Prefixes.Add($"http://127.0.0.1:{PORT}/work/"); |
|
311 |
//server.Prefixes.Add($"http://{ip}:{PORT}/work/"); |
|
312 |
//server.Prefixes.Add($"http://+:{PORT}/work/"); |
|
313 |
|
|
314 |
server.Start(); |
|
315 |
|
|
316 |
Console.WriteLine("Listening..."); |
|
317 |
|
|
318 |
while (true) |
|
319 |
{ |
|
320 |
Console.WriteLine("waiting for request?"); |
|
321 |
//Console.ReadLine(); |
|
322 |
|
|
323 |
HttpListenerContext context = server.GetContext(); |
|
324 |
|
|
325 |
|
|
326 |
if (context.Request.HttpMethod == "GET") // when client says download |
|
327 |
{ |
|
328 |
HttpListenerResponse response = context.Response; |
|
329 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
330 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
331 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
332 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
333 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
334 |
|
|
335 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; |
|
336 |
// if (page == string.Empty) |
|
337 |
// page = "test.txt"; |
|
338 |
// |
|
339 |
// TextReader tr = new StreamReader(page); |
|
340 |
// string msg = tr.ReadToEnd(); |
|
341 |
|
|
342 |
int rand = new Random().Next(1, 10); |
|
343 |
string msg = "This is a response from the server :) " + rand; |
|
344 |
|
|
345 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
346 |
|
|
347 |
response.ContentLength64 = buffer.Length; |
|
348 |
Stream st = response.OutputStream; |
|
349 |
st.Write(buffer, 0, buffer.Length); |
|
350 |
|
|
351 |
|
|
352 |
context.Response.Close(); |
|
353 |
} |
|
354 |
|
|
355 |
else if (context.Request.HttpMethod == "POST") // when client says upload |
|
356 |
{ |
|
357 |
string text; |
|
358 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) |
|
359 |
text = reader.ReadToEnd(); |
|
360 |
Console.WriteLine("Received request:"); |
|
361 |
Console.WriteLine(HttpUtility.UrlDecode(text)); |
|
362 |
|
|
363 |
context.Response.Close(); |
|
364 |
} |
|
365 |
} |
|
366 |
} |
|
367 |
|
|
368 |
|
|
369 |
private string GetLocalIPAddress() |
|
370 |
{ |
|
371 |
var host = Dns.GetHostEntry(Dns.GetHostName()); |
|
372 |
foreach (var ip in host.AddressList) |
|
373 |
{ |
|
374 |
if (ip.AddressFamily == AddressFamily.InterNetwork) |
|
375 |
{ |
|
376 |
return ip.ToString(); |
|
377 |
} |
|
378 |
} |
|
379 |
throw new Exception("No network adapters with an IPv4 address in the system!"); |
|
380 |
} |
|
381 |
|
|
382 |
} |
|
383 |
|
|
384 |
} |
Server/ServerApp/Connection/SocketListener.cs | ||
---|---|---|
1 |
// |
|
2 |
// Author: Eliska Mourycova |
|
3 |
// |
|
4 |
|
|
5 |
using System; |
|
6 |
using System.IO; |
|
7 |
using System.Net; |
|
8 |
using System.Net.Sockets; |
|
9 |
using System.Text; |
|
10 |
using System.Threading; |
|
11 |
using System.Web; |
|
12 |
|
|
13 |
namespace ServerApp.Connection |
|
14 |
{ |
|
15 |
// /// <summary> |
|
16 |
// /// State object for reading client data asynchronously |
|
17 |
// /// </summary> |
|
18 |
// public class StateObject |
|
19 |
// { |
|
20 |
// // Client socket. |
|
21 |
// public Socket WorkSocket = null; |
|
22 |
// // Size of receive buffer. |
|
23 |
// public const int BUFFER_SIZE = 1024; |
|
24 |
// // Receive buffer. |
|
25 |
// public byte[] Buffer = new byte[BUFFER_SIZE]; |
|
26 |
// // Received data string. |
|
27 |
// public StringBuilder StrBuilder = new StringBuilder(); |
|
28 |
// } |
|
29 |
|
|
30 |
// /// <summary> |
|
31 |
// /// This class takes care of client connection. It serves clients asynchronously. |
|
32 |
// /// </summary> |
|
33 |
// public class AsynchronousSocketListener |
|
34 |
// { |
|
35 |
// // port numbers: |
|
36 |
// private const int PORT_NO = 11000; |
|
37 |
// private const int ADMIN_PORT_NO = 10000; |
|
38 |
|
|
39 |
|
|
40 |
// // Thread signal |
|
41 |
// private ManualResetEvent allDone = new ManualResetEvent(false); |
|
42 |
|
|
43 |
// /// <summary> |
|
44 |
// /// Starts listening and accepting connections. It serves requests when they come. |
|
45 |
// /// </summary> |
|
46 |
// public void StartListening() |
|
47 |
// { |
|
48 |
// // Data buffer for incoming data. |
|
49 |
// byte[] bytes = new Byte[1024]; |
|
50 |
|
|
51 |
// // Establish the local endpoint for the socket: |
|
52 |
// IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); |
|
53 |
|
|
54 |
// // Get the IP of the machine - UNUSED ATM, USING LOOPBACK ON LOCALHOST |
|
55 |
// IPAddress ipAddress = ipHostInfo.AddressList[1]; |
|
56 |
// Console.WriteLine("machine ip: " + ipAddress.ToString()); |
|
57 |
// IPEndPoint localEndPoint = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, PORT_NO); |
|
58 |
// IPEndPoint localEndPointAdmin = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, ADMIN_PORT_NO); |
|
59 |
|
|
60 |
// // Create a TCP/IP socket. |
|
61 |
// Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
|
62 |
// Socket listenerAdmin = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
|
63 |
|
|
64 |
// // Bind the socket to the local endpoint and listen for incoming connections. |
|
65 |
// try |
|
66 |
// { |
|
67 |
// listener.Bind(localEndPoint); |
|
68 |
// listener.Listen(100); |
|
69 |
|
|
70 |
// listenerAdmin.Bind(localEndPointAdmin); |
|
71 |
// listenerAdmin.Listen(1); |
|
72 |
|
|
73 |
// // keep accepting |
|
74 |
// while (true) |
|
75 |
// { |
|
76 |
// // Set the event to nonsignaled state. |
|
77 |
// allDone.Reset(); |
|
78 |
|
|
79 |
// // Start an asynchronous socket to listen for connections. |
|
80 |
// Console.WriteLine("Waiting for a connection..."); |
|
81 |
// listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); |
|
82 |
// listenerAdmin.BeginAccept(new AsyncCallback(AcceptCallback), listenerAdmin); |
|
83 |
|
|
84 |
// // Wait until a connection is made before continuing. |
|
85 |
// allDone.WaitOne(); |
|
86 |
// } |
|
87 |
|
|
88 |
// } |
|
89 |
// catch (Exception e) |
|
90 |
// { |
|
91 |
// // bind failed |
|
92 |
// Console.WriteLine(e.ToString()); |
|
93 |
// } |
|
94 |
|
|
95 |
// Console.WriteLine("\nPress ENTER to continue..."); |
|
96 |
// Console.Read(); |
|
97 |
|
|
98 |
// } |
|
99 |
|
|
100 |
// // Routine for when BeginAccept on the given listener ended |
|
101 |
// private void AcceptCallback(IAsyncResult ar) |
|
102 |
// { |
|
103 |
// // Signal the main thread to continue. |
|
104 |
// allDone.Set(); |
|
105 |
// Console.WriteLine("Accepted a connection."); |
|
106 |
|
|
107 |
|
|
108 |
// // Get the socket that handles the client request. |
|
109 |
// Socket listener = (Socket)ar.AsyncState; |
|
110 |
// Socket handler = listener.EndAccept(ar); |
|
111 |
|
|
112 |
// // debug |
|
113 |
// Console.WriteLine("handler: "); |
|
114 |
// Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)handler.RemoteEndPoint).Address.ToString()) + " on port number " + ((IPEndPoint)handler.RemoteEndPoint).Port.ToString()); |
|
115 |
// Console.WriteLine("My local IpAddress is : " + IPAddress.Parse(((IPEndPoint)handler.LocalEndPoint).Address.ToString()) + ". I am connected on port number " + ((IPEndPoint)handler.LocalEndPoint).Port.ToString()); |
|
116 |
|
|
117 |
|
|
118 |
|
|
119 |
|
|
120 |
// // Create the state object. |
|
121 |
// StateObject state = new StateObject(); |
|
122 |
// state.WorkSocket = handler; |
|
123 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
124 |
|
|
125 |
// } |
|
126 |
|
|
127 |
// // Routine for when BeginReceive on the given listener ended |
|
128 |
// private void ReadCallback(IAsyncResult ar) |
|
129 |
// { |
|
130 |
// // string for the received message |
|
131 |
// String content = String.Empty; |
|
132 |
|
|
133 |
// // Retrieve the state object and the handler socket |
|
134 |
// // from the asynchronous state object. |
|
135 |
// StateObject state = (StateObject)ar.AsyncState; |
|
136 |
// Socket handler = state.WorkSocket; |
|
137 |
|
|
138 |
// // check if we're still connected |
|
139 |
// if (!SocketConnected(handler)) |
|
140 |
// { |
|
141 |
// // if the client isn't connected anymore, take care of cleanup |
|
142 |
// Console.WriteLine("Closing connection - unexpected..."); |
|
143 |
// CloseConnection(handler); |
|
144 |
|
|
145 |
// // return so that we don't attempt to read from a non-existent stream |
|
146 |
// return; |
|
147 |
// } |
|
148 |
|
|
149 |
// // check if it is admin's request we're serving |
|
150 |
// bool admin = ((IPEndPoint)handler.LocalEndPoint).Port == ADMIN_PORT_NO; |
|
151 |
|
|
152 |
// // Read data from the client socket. |
|
153 |
// int bytesRead = handler.EndReceive(ar); |
|
154 |
|
|
155 |
// if (bytesRead > 0) |
|
156 |
// { |
|
157 |
// // There might be more data, so store the data received so far. |
|
158 |
// state.StrBuilder.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead)); |
|
159 |
|
|
160 |
// // Check for end-of-file tag. If it is not there, read more data. |
|
161 |
// content = state.StrBuilder.ToString(); |
|
162 |
// if (content.IndexOf("!") > -1) |
|
163 |
// { |
|
164 |
// // All the data has been read from the client. Display it on the console. |
|
165 |
// Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); |
|
166 |
|
|
167 |
// // parse the message and determine the response: |
|
168 |
// content = ParseMessageAndBuildAnswer(content, admin); |
|
169 |
|
|
170 |
// // check if the client wishes to close the connection: |
|
171 |
// if (content.Equals("bye!")) |
|
172 |
// { |
|
173 |
// Console.WriteLine("Closing connection - expected..."); |
|
174 |
// //handler.Shutdown(SocketShutdown.Both); |
|
175 |
// //handler.Close(); |
|
176 |
// CloseConnection(handler); |
|
177 |
// return; |
|
178 |
// } |
|
179 |
|
|
180 |
// // Send a response to the client |
|
181 |
// Send(handler, content); |
|
182 |
|
|
183 |
// // clear the string |
|
184 |
// state.StrBuilder.Clear(); |
|
185 |
|
|
186 |
// // begin receiving another message: |
|
187 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
188 |
// } |
|
189 |
// else |
|
190 |
// { |
|
191 |
// // Not all data received. Get more. |
|
192 |
// handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state); |
|
193 |
// } |
|
194 |
// } |
|
195 |
// } |
|
196 |
|
|
197 |
// // Takes care of sending data to a connected client |
|
198 |
// private void Send(Socket handler, String data) |
|
199 |
// { |
|
200 |
// // Convert the string data to byte data using ASCII encoding. |
|
201 |
// byte[] byteData = Encoding.ASCII.GetBytes(data); |
|
202 |
|
|
203 |
// // Begin sending the data to the remote device. |
|
204 |
// handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); |
|
205 |
// } |
|
206 |
|
|
207 |
// // Routine for when BeginSend on the given listener ended |
|
208 |
// private void SendCallback(IAsyncResult ar) |
|
209 |
// { |
|
210 |
// try |
|
211 |
// { |
|
212 |
// // Retrieve the socket from the state object. |
|
213 |
// Socket handler = (Socket)ar.AsyncState; |
|
214 |
|
|
215 |
// // Complete sending the data to the remote device. |
|
216 |
// int bytesSent = handler.EndSend(ar); |
|
217 |
// Console.WriteLine("Sent {0} bytes to client.", bytesSent); |
|
218 |
|
|
219 |
|
|
220 |
// //handler.Shutdown(SocketShutdown.Both); |
|
221 |
// //handler.Close(); |
|
222 |
|
|
223 |
// } |
|
224 |
// catch (Exception e) |
|
225 |
// { |
|
226 |
// // close connection here? |
|
227 |
|
|
228 |
// Console.WriteLine(e.ToString()); |
|
229 |
// } |
|
230 |
// } |
|
231 |
|
|
232 |
|
|
233 |
// /// <summary> |
|
234 |
// /// Parses the incoming request and determines the response. |
|
235 |
// /// </summary> |
|
236 |
// /// <param name="message">The incoming message from the client</param> |
|
237 |
// /// <param name="admin">A flag saying whether it is admin's request</param> |
|
238 |
// /// <returns></returns> |
|
239 |
// private string ParseMessageAndBuildAnswer(string message, bool admin) |
|
240 |
//{ |
|
241 |
// Console.WriteLine("Parsing message from admin: " + admin); |
|
242 |
// string ans = ""; |
|
243 |
|
|
244 |
// if (message.Equals("hello!")) |
|
245 |
// { |
|
246 |
// ans = "hello to you too."; |
|
247 |
// } |
|
248 |
// else if (message.Equals("weather!")) |
|
249 |
// { |
|
250 |
// ans = "weather will be nice"; |
|
251 |
// } |
|
252 |
// else if (message.Equals("bye!")) |
|
253 |
// { |
|
254 |
// ans = "bye!"; |
|
255 |
// } |
|
256 |
// else |
|
257 |
// { |
|
258 |
// // here bye too, if we want to disconnect clients who don't follow protocol |
|
259 |
// ans = "bye!";//"i didnt understand that"; |
|
260 |
|
|
261 |
// } |
|
262 |
|
|
263 |
// return ans; |
|
264 |
//} |
|
265 |
|
|
266 |
// /// <summary> |
|
267 |
// /// Closes the connection on the passed Socket |
|
268 |
// /// </summary> |
|
269 |
// /// <param name="s">The socket to close the connection for</param> |
|
270 |
// private void CloseConnection(Socket s) |
|
271 |
//{ |
|
272 |
// s.Shutdown(SocketShutdown.Both); |
|
273 |
// s.Close(); |
|
274 |
// } |
|
275 |
|
|
276 |
// /// <summary> |
|
277 |
// /// Checks whether the connection on a given socket is active |
|
278 |
// /// </summary> |
|
279 |
// /// <param name="s">The socket to check for connection activity</param> |
|
280 |
// /// <returns>True if the connection is active, false otherwise</returns> |
|
281 |
// private bool SocketConnected(Socket s) |
|
282 |
// { |
|
283 |
// bool part1 = s.Poll(1000, SelectMode.SelectRead); |
|
284 |
// bool part2 = (s.Available == 0); |
|
285 |
// if (part1 && part2) |
|
286 |
// return false; |
|
287 |
// else |
|
288 |
// return true; |
|
289 |
// } |
|
290 |
// } |
|
291 |
|
|
292 |
|
|
293 |
public class ConnectionListener |
|
294 |
{ |
|
295 |
private readonly int PORT; |
|
296 |
|
|
297 |
public ConnectionListener(int port) |
|
298 |
{ |
|
299 |
this.PORT = port; |
|
300 |
} |
|
301 |
|
|
302 |
public void StartListening() |
|
303 |
{ |
|
304 |
string ip = GetLocalIPAddress(); |
|
305 |
Console.WriteLine("ip : " + ip); |
|
306 |
HttpListener server = new HttpListener(); |
|
307 |
server.Prefixes.Add("http://*:8000/work/"); |
|
308 |
server.Prefixes.Add("http://localhost:8000/work/"); |
|
309 |
server.Prefixes.Add("http://127.0.0.1:8000/work/"); |
|
310 |
server.Prefixes.Add($"http://{ip}:8000/work/"); |
|
311 |
server.Prefixes.Add("http://+:8000/work/"); |
|
312 |
|
|
313 |
server.Start(); |
|
314 |
|
|
315 |
Console.WriteLine("Listening..."); |
|
316 |
|
|
317 |
while (true) |
|
318 |
{ |
|
319 |
Console.WriteLine("waiting for request?"); |
|
320 |
//Console.ReadLine(); |
|
321 |
|
|
322 |
HttpListenerContext context = server.GetContext(); |
|
323 |
|
|
324 |
|
|
325 |
if (context.Request.HttpMethod == "GET") // when client says download |
|
326 |
{ |
|
327 |
HttpListenerResponse response = context.Response; |
|
328 |
response.AddHeader("Access-Control-Allow-Credentials", "true"); |
|
329 |
response.AddHeader("Access-Control-Expose-Headers", "ETag"); |
|
330 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"); |
|
331 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
|
332 |
response.AddHeader("Access-Control-Allow-Origin", "*"); |
|
333 |
|
|
334 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; |
|
335 |
// if (page == string.Empty) |
|
336 |
// page = "test.txt"; |
|
337 |
// |
|
338 |
// TextReader tr = new StreamReader(page); |
|
339 |
// string msg = tr.ReadToEnd(); |
|
340 |
|
|
341 |
int rand = new Random().Next(1, 10); |
|
342 |
string msg = "This is a response from the server :) " + rand; |
|
343 |
|
|
344 |
byte[] buffer = Encoding.UTF8.GetBytes(msg); |
|
345 |
|
|
346 |
response.ContentLength64 = buffer.Length; |
|
347 |
Stream st = response.OutputStream; |
|
348 |
st.Write(buffer, 0, buffer.Length); |
|
349 |
|
|
350 |
|
|
351 |
context.Response.Close(); |
|
352 |
} |
|
353 |
|
|
354 |
else if (context.Request.HttpMethod == "POST") // when client says upload |
|
355 |
{ |
|
356 |
string text; |
|
357 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) |
|
358 |
text = reader.ReadToEnd(); |
|
359 |
Console.WriteLine("Received request:"); |
|
360 |
Console.WriteLine(HttpUtility.UrlDecode(text)); |
|
361 |
|
|
362 |
context.Response.Close(); |
|
363 |
} |
|
364 |
} |
|
365 |
} |
|
366 |
|
|
367 |
|
|
368 |
private string GetLocalIPAddress() |
|
369 |
{ |
|
370 |
var host = Dns.GetHostEntry(Dns.GetHostName()); |
|
371 |
foreach (var ip in host.AddressList) |
|
372 |
{ |
|
373 |
if (ip.AddressFamily == AddressFamily.InterNetwork) |
|
374 |
{ |
|
375 |
return ip.ToString(); |
|
376 |
} |
|
377 |
} |
|
378 |
throw new Exception("No network adapters with an IPv4 address in the system!"); |
|
379 |
} |
|
380 |
} |
|
381 |
|
|
382 |
} |
Server/ServerApp/Program.cs | ||
---|---|---|
30 | 30 |
static void Main(string[] args) |
31 | 31 |
{ |
32 | 32 |
|
33 |
// Config config = FillConfigInfo(args);
|
|
34 |
//if (config == null)
|
|
35 |
//{
|
|
36 |
// Console.ReadLine();
|
|
37 |
// return;
|
|
38 |
//}
|
|
33 |
Config config = FillConfigInfo(args);
|
|
34 |
if (config == null) |
|
35 |
{ |
|
36 |
Console.ReadLine(); |
|
37 |
return; |
|
38 |
} |
|
39 | 39 |
|
40 |
// create a thread for commands accepting:
|
|
41 |
//Thread inputThread = new Thread(CommandsAcceptor.AcceptCommand);
|
|
42 |
//inputThread.Start();
|
|
40 |
//create a thread for commands accepting: |
|
41 |
Thread inputThread = new Thread(CommandsAcceptor.AcceptCommand); |
|
42 |
inputThread.Start(); |
|
43 | 43 |
|
44 | 44 |
|
45 | 45 |
|
46 | 46 |
//DataParser p = new DataParser("data/"); |
47 |
|
|
48 | 47 |
//p.Parse(); |
49 | 48 |
|
50 | 49 |
|
51 |
// test scenario - data download:
|
|
52 |
//DataDownloader dd = new DataDownloader(config.DataRootDir, config.DataWebsite, config.DownloadedFilesNaming);
|
|
53 |
//dd.OverwriteExisting = false;
|
|
54 |
//List<string> savedFiles = new List<string>();
|
|
55 |
////savedFiles.AddRange(dd.DownloadData(DataType.JIS, DataFormat.CSV, new Date(1, 2019), new Date(12, 2020)));
|
|
56 |
////savedFiles.AddRange(dd.DownloadData(DataType.STROJE, DataFormat.CSV, new Date(1, 2017), new Date(12, 2020)));
|
|
57 |
////savedFiles.AddRange(dd.DownloadData(DataType.POCASI, DataFormat.CSV, new Date(1, 2017), new Date(12, 2020)));
|
|
50 |
//test scenario -data download:
|
|
51 |
DataDownloader dd = new DataDownloader(config.DataRootDir, config.DataWebsite, config.DownloadedFilesNaming); |
|
52 |
dd.OverwriteExisting = false; |
|
53 |
List<string> savedFiles = new List<string>(); |
|
54 |
savedFiles.AddRange(dd.DownloadData(DataType.JIS, DataFormat.CSV, new Date(1, 2019), new Date(12, 2020))); |
|
55 |
savedFiles.AddRange(dd.DownloadData(DataType.STROJE, DataFormat.CSV, new Date(1, 2017), new Date(12, 2020))); |
|
56 |
savedFiles.AddRange(dd.DownloadData(DataType.POCASI, DataFormat.CSV, new Date(1, 2017), new Date(12, 2020))); |
|
58 | 57 |
|
59 | 58 |
|
60 | 59 |
|
61 |
//Console.WriteLine("Saved files: ");
|
|
62 |
//foreach (string s in savedFiles)
|
|
63 |
//{
|
|
64 |
// Console.WriteLine(s);
|
|
65 |
//}
|
|
60 |
Console.WriteLine("Saved files: "); |
|
61 |
foreach (string s in savedFiles) |
|
62 |
{ |
|
63 |
Console.WriteLine(s); |
|
64 |
} |
|
66 | 65 |
|
67 |
//Console.WriteLine("subdirectories: ");
|
|
68 |
//foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories)
|
|
69 |
//{
|
|
70 |
// Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
|
|
71 |
//}
|
|
66 |
Console.WriteLine("subdirectories: "); |
|
67 |
foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories) |
|
68 |
{ |
|
69 |
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); |
|
70 |
} |
|
72 | 71 |
|
73 |
//List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new Date(10, 2019), new Date(12, 2020));
|
|
74 |
//Console.WriteLine("Retrieved data: ");
|
|
75 |
//foreach (string s in retrievedData)
|
|
76 |
//{
|
|
77 |
// Console.WriteLine(s);
|
|
78 |
//}
|
|
72 |
List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new Date(10, 2019), new Date(12, 2020)); |
|
73 |
Console.WriteLine("Retrieved data: "); |
|
74 |
foreach (string s in retrievedData) |
|
75 |
{ |
|
76 |
Console.WriteLine(s); |
|
77 |
} |
|
79 | 78 |
|
80 | 79 |
|
81 | 80 |
|
82 | 81 |
|
83 | 82 |
|
84 | 83 |
// test - connection: |
85 |
ConnectionListener cl = new ConnectionListener(8000/*int.Parse(config.Port)*/);
|
|
86 |
cl.StartListening(); |
|
84 |
//ConnectionListener cl = new ConnectionListener(int.Parse(args[0])/*8000*//*int.Parse(config.Port)*/);
|
|
85 |
//cl.StartListening();
|
|
87 | 86 |
|
88 | 87 |
|
89 | 88 |
//NaiveBayesClassifier naiveBayesClassifier = new NaiveBayesClassifier(); |
Server/ServerApp/ServerApp.csproj | ||
---|---|---|
130 | 130 |
<Reference Include="System.Xml" /> |
131 | 131 |
</ItemGroup> |
132 | 132 |
<ItemGroup> |
133 |
<Compile Include="Connection\SocketListener.cs" />
|
|
133 |
<Compile Include="Connection\ConnectionListener.cs" />
|
|
134 | 134 |
<Compile Include="DataDownload\DataDownloader.cs" /> |
135 | 135 |
<Compile Include="DataDownload\Date.cs" /> |
136 | 136 |
<Compile Include="Parser\InputData\CsvDataLoader.cs" /> |
Také k dispozici: Unified diff
Re #8770. Refactoring