3 |
3 |
//
|
4 |
4 |
|
5 |
5 |
using System;
|
|
6 |
using System.IO;
|
6 |
7 |
using System.Net;
|
7 |
8 |
using System.Net.Sockets;
|
8 |
9 |
using System.Text;
|
9 |
10 |
using System.Threading;
|
|
11 |
using System.Web;
|
10 |
12 |
|
11 |
13 |
namespace ServerApp.Connection
|
12 |
14 |
{
|
13 |
|
/// <summary>
|
14 |
|
/// State object for reading client data asynchronously
|
15 |
|
/// </summary>
|
16 |
|
public class StateObject
|
17 |
|
{
|
18 |
|
// Client socket.
|
19 |
|
public Socket WorkSocket = null;
|
20 |
|
// Size of receive buffer.
|
21 |
|
public const int BUFFER_SIZE = 1024;
|
22 |
|
// Receive buffer.
|
23 |
|
public byte[] Buffer = new byte[BUFFER_SIZE];
|
24 |
|
// Received data string.
|
25 |
|
public StringBuilder StrBuilder = new StringBuilder();
|
26 |
|
}
|
27 |
|
|
28 |
|
/// <summary>
|
29 |
|
/// This class takes care of client connection. It serves clients asynchronously.
|
30 |
|
/// </summary>
|
31 |
|
public class AsynchronousSocketListener
|
32 |
|
{
|
33 |
|
// port numbers:
|
34 |
|
private const int PORT_NO = 11000;
|
35 |
|
private const int ADMIN_PORT_NO = 10000;
|
36 |
|
|
37 |
|
|
38 |
|
// Thread signal
|
39 |
|
private ManualResetEvent allDone = new ManualResetEvent(false);
|
40 |
|
|
41 |
|
/// <summary>
|
42 |
|
/// Starts listening and accepting connections. It serves requests when they come.
|
43 |
|
/// </summary>
|
44 |
|
public void StartListening()
|
45 |
|
{
|
46 |
|
// Data buffer for incoming data.
|
47 |
|
byte[] bytes = new Byte[1024];
|
48 |
|
|
49 |
|
// Establish the local endpoint for the socket:
|
50 |
|
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
|
51 |
|
|
52 |
|
// Get the IP of the machine - UNUSED ATM, USING LOOPBACK ON LOCALHOST
|
53 |
|
IPAddress ipAddress = ipHostInfo.AddressList[1];
|
54 |
|
Console.WriteLine("machine ip: " + ipAddress.ToString());
|
55 |
|
IPEndPoint localEndPoint = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, PORT_NO);
|
56 |
|
IPEndPoint localEndPointAdmin = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, ADMIN_PORT_NO);
|
57 |
|
|
58 |
|
// Create a TCP/IP socket.
|
59 |
|
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
60 |
|
Socket listenerAdmin = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
61 |
|
|
62 |
|
// Bind the socket to the local endpoint and listen for incoming connections.
|
63 |
|
try
|
64 |
|
{
|
65 |
|
listener.Bind(localEndPoint);
|
66 |
|
listener.Listen(100);
|
67 |
|
|
68 |
|
listenerAdmin.Bind(localEndPointAdmin);
|
69 |
|
listenerAdmin.Listen(1);
|
70 |
|
|
71 |
|
// keep accepting
|
72 |
|
while (true)
|
73 |
|
{
|
74 |
|
// Set the event to nonsignaled state.
|
75 |
|
allDone.Reset();
|
76 |
|
|
77 |
|
// Start an asynchronous socket to listen for connections.
|
78 |
|
Console.WriteLine("Waiting for a connection...");
|
79 |
|
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
|
80 |
|
listenerAdmin.BeginAccept(new AsyncCallback(AcceptCallback), listenerAdmin);
|
81 |
|
|
82 |
|
// Wait until a connection is made before continuing.
|
83 |
|
allDone.WaitOne();
|
84 |
|
}
|
85 |
|
|
86 |
|
}
|
87 |
|
catch (Exception e)
|
88 |
|
{
|
89 |
|
// bind failed
|
90 |
|
Console.WriteLine(e.ToString());
|
91 |
|
}
|
92 |
|
|
93 |
|
Console.WriteLine("\nPress ENTER to continue...");
|
94 |
|
Console.Read();
|
95 |
|
|
96 |
|
}
|
97 |
|
|
98 |
|
// Routine for when BeginAccept on the given listener ended
|
99 |
|
private void AcceptCallback(IAsyncResult ar)
|
100 |
|
{
|
101 |
|
// Signal the main thread to continue.
|
102 |
|
allDone.Set();
|
103 |
|
Console.WriteLine("Accepted a connection.");
|
|
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.");
|
104 |
106 |
|
105 |
107 |
|
106 |
|
// Get the socket that handles the client request.
|
107 |
|
Socket listener = (Socket)ar.AsyncState;
|
108 |
|
Socket handler = listener.EndAccept(ar);
|
|
108 |
// // Get the socket that handles the client request.
|
|
109 |
// Socket listener = (Socket)ar.AsyncState;
|
|
110 |
// Socket handler = listener.EndAccept(ar);
|
109 |
111 |
|
110 |
|
// debug
|
111 |
|
Console.WriteLine("handler: ");
|
112 |
|
Console.WriteLine("I am connected to " + IPAddress.Parse(((IPEndPoint)handler.RemoteEndPoint).Address.ToString()) + " on port number " + ((IPEndPoint)handler.RemoteEndPoint).Port.ToString());
|
113 |
|
Console.WriteLine("My local IpAddress is : " + IPAddress.Parse(((IPEndPoint)handler.LocalEndPoint).Address.ToString()) + ". I am connected on port number " + ((IPEndPoint)handler.LocalEndPoint).Port.ToString());
|
|
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());
|
114 |
116 |
|
115 |
117 |
|
116 |
118 |
|
117 |
119 |
|
118 |
|
// Create the state object.
|
119 |
|
StateObject state = new StateObject();
|
120 |
|
state.WorkSocket = handler;
|
121 |
|
handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state);
|
|
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);
|
122 |
124 |
|
123 |
|
}
|
|
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 |
}
|
124 |
301 |
|
125 |
|
// Routine for when BeginReceive on the given listener ended
|
126 |
|
private void ReadCallback(IAsyncResult ar)
|
127 |
|
{
|
128 |
|
// string for the received message
|
129 |
|
String content = String.Empty;
|
130 |
|
|
131 |
|
// Retrieve the state object and the handler socket
|
132 |
|
// from the asynchronous state object.
|
133 |
|
StateObject state = (StateObject)ar.AsyncState;
|
134 |
|
Socket handler = state.WorkSocket;
|
135 |
|
|
136 |
|
// check if we're still connected
|
137 |
|
if (!SocketConnected(handler))
|
138 |
|
{
|
139 |
|
// if the client isn't connected anymore, take care of cleanup
|
140 |
|
Console.WriteLine("Closing connection - unexpected...");
|
141 |
|
CloseConnection(handler);
|
142 |
|
|
143 |
|
// return so that we don't attempt to read from a non-existent stream
|
144 |
|
return;
|
145 |
|
}
|
|
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/");
|
146 |
312 |
|
147 |
|
// check if it is admin's request we're serving
|
148 |
|
bool admin = ((IPEndPoint)handler.LocalEndPoint).Port == ADMIN_PORT_NO;
|
|
313 |
server.Start();
|
149 |
314 |
|
150 |
|
// Read data from the client socket.
|
151 |
|
int bytesRead = handler.EndReceive(ar);
|
|
315 |
Console.WriteLine("Listening...");
|
152 |
316 |
|
153 |
|
if (bytesRead > 0)
|
|
317 |
while (true)
|
154 |
318 |
{
|
155 |
|
// There might be more data, so store the data received so far.
|
156 |
|
state.StrBuilder.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead));
|
|
319 |
Console.WriteLine("waiting for request?");
|
|
320 |
//Console.ReadLine();
|
157 |
321 |
|
158 |
|
// Check for end-of-file tag. If it is not there, read more data.
|
159 |
|
content = state.StrBuilder.ToString();
|
160 |
|
if (content.IndexOf("!") > -1)
|
161 |
|
{
|
162 |
|
// All the data has been read from the client. Display it on the console.
|
163 |
|
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
|
164 |
|
|
165 |
|
// parse the message and determine the response:
|
166 |
|
content = ParseMessageAndBuildAnswer(content, admin);
|
167 |
|
|
168 |
|
// check if the client wishes to close the connection:
|
169 |
|
if (content.Equals("bye!"))
|
170 |
|
{
|
171 |
|
Console.WriteLine("Closing connection - expected...");
|
172 |
|
//handler.Shutdown(SocketShutdown.Both);
|
173 |
|
//handler.Close();
|
174 |
|
CloseConnection(handler);
|
175 |
|
return;
|
176 |
|
}
|
177 |
|
|
178 |
|
// Send a response to the client
|
179 |
|
Send(handler, content);
|
180 |
|
|
181 |
|
// clear the string
|
182 |
|
state.StrBuilder.Clear();
|
|
322 |
HttpListenerContext context = server.GetContext();
|
183 |
323 |
|
184 |
|
// begin receiving another message:
|
185 |
|
handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state);
|
|
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();
|
186 |
352 |
}
|
187 |
|
else
|
|
353 |
|
|
354 |
else if (context.Request.HttpMethod == "POST") // when client says upload
|
188 |
355 |
{
|
189 |
|
// Not all data received. Get more.
|
190 |
|
handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state);
|
|
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();
|
191 |
363 |
}
|
192 |
364 |
}
|
193 |
365 |
}
|
194 |
366 |
|
195 |
|
// Takes care of sending data to a connected client
|
196 |
|
private void Send(Socket handler, String data)
|
197 |
|
{
|
198 |
|
// Convert the string data to byte data using ASCII encoding.
|
199 |
|
byte[] byteData = Encoding.ASCII.GetBytes(data);
|
200 |
|
|
201 |
|
// Begin sending the data to the remote device.
|
202 |
|
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
|
203 |
|
}
|
204 |
367 |
|
205 |
|
// Routine for when BeginSend on the given listener ended
|
206 |
|
private void SendCallback(IAsyncResult ar)
|
|
368 |
private string GetLocalIPAddress()
|
207 |
369 |
{
|
208 |
|
try
|
209 |
|
{
|
210 |
|
// Retrieve the socket from the state object.
|
211 |
|
Socket handler = (Socket)ar.AsyncState;
|
212 |
|
|
213 |
|
// Complete sending the data to the remote device.
|
214 |
|
int bytesSent = handler.EndSend(ar);
|
215 |
|
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
|
216 |
|
|
217 |
|
|
218 |
|
//handler.Shutdown(SocketShutdown.Both);
|
219 |
|
//handler.Close();
|
220 |
|
|
221 |
|
}
|
222 |
|
catch (Exception e)
|
|
370 |
var host = Dns.GetHostEntry(Dns.GetHostName());
|
|
371 |
foreach (var ip in host.AddressList)
|
223 |
372 |
{
|
224 |
|
// close connection here?
|
225 |
|
|
226 |
|
Console.WriteLine(e.ToString());
|
227 |
|
}
|
228 |
|
}
|
229 |
|
|
230 |
|
|
231 |
|
/// <summary>
|
232 |
|
/// Parses the incoming request and determines the response.
|
233 |
|
/// </summary>
|
234 |
|
/// <param name="message">The incoming message from the client</param>
|
235 |
|
/// <param name="admin">A flag saying whether it is admin's request</param>
|
236 |
|
/// <returns></returns>
|
237 |
|
private string ParseMessageAndBuildAnswer(string message, bool admin)
|
238 |
|
{
|
239 |
|
Console.WriteLine("Parsing message from admin: " + admin);
|
240 |
|
string ans = "";
|
241 |
|
|
242 |
|
if (message.Equals("hello!"))
|
243 |
|
{
|
244 |
|
ans = "hello to you too.";
|
245 |
|
}
|
246 |
|
else if (message.Equals("weather!"))
|
247 |
|
{
|
248 |
|
ans = "weather will be nice";
|
249 |
|
}
|
250 |
|
else if (message.Equals("bye!"))
|
251 |
|
{
|
252 |
|
ans = "bye!";
|
253 |
|
}
|
254 |
|
else
|
255 |
|
{
|
256 |
|
// here bye too, if we want to disconnect clients who don't follow protocol
|
257 |
|
ans = "bye!";//"i didnt understand that";
|
258 |
|
|
|
373 |
if (ip.AddressFamily == AddressFamily.InterNetwork)
|
|
374 |
{
|
|
375 |
return ip.ToString();
|
|
376 |
}
|
259 |
377 |
}
|
260 |
|
|
261 |
|
return ans;
|
262 |
|
}
|
263 |
|
|
264 |
|
/// <summary>
|
265 |
|
/// Closes the connection on the passed Socket
|
266 |
|
/// </summary>
|
267 |
|
/// <param name="s">The socket to close the connection for</param>
|
268 |
|
private void CloseConnection(Socket s)
|
269 |
|
{
|
270 |
|
s.Shutdown(SocketShutdown.Both);
|
271 |
|
s.Close();
|
272 |
|
}
|
273 |
|
|
274 |
|
/// <summary>
|
275 |
|
/// Checks whether the connection on a given socket is active
|
276 |
|
/// </summary>
|
277 |
|
/// <param name="s">The socket to check for connection activity</param>
|
278 |
|
/// <returns>True if the connection is active, false otherwise</returns>
|
279 |
|
private bool SocketConnected(Socket s)
|
280 |
|
{
|
281 |
|
bool part1 = s.Poll(1000, SelectMode.SelectRead);
|
282 |
|
bool part2 = (s.Available == 0);
|
283 |
|
if (part1 && part2)
|
284 |
|
return false;
|
285 |
|
else
|
286 |
|
return true;
|
|
378 |
throw new Exception("No network adapters with an IPv4 address in the system!");
|
287 |
379 |
}
|
288 |
380 |
}
|
289 |
381 |
|
Re #8770. Somewhat working example of HttpListener. Can receive requests from other than host machine. Firawall adjustment was necessary.