12 |
12 |
|
13 |
13 |
namespace ServerApp.Connection
|
14 |
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 |
|
{
|
|
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 |
304 |
string ip = GetLocalIPAddress();
|
305 |
305 |
Console.WriteLine("ip : " + ip);
|
306 |
306 |
HttpListener server = new HttpListener();
|
307 |
|
server.Prefixes.Add($"http://*:{PORT}/work/");
|
308 |
|
server.Prefixes.Add($"https://*:{PORT}/work2/");
|
|
307 |
//server.Prefixes.Add($"http://*:1234/work/");
|
|
308 |
server.Prefixes.Add($"https://{ip}:{PORT}/");
|
309 |
309 |
//server.Prefixes.Add($"http://localhost:{PORT}/work/");
|
310 |
310 |
//server.Prefixes.Add($"http://127.0.0.1:{PORT}/work/");
|
311 |
311 |
//server.Prefixes.Add($"http://{ip}:{PORT}/work/");
|
... | ... | |
325 |
325 |
|
326 |
326 |
if (context.Request.HttpMethod == "GET") // when client says download
|
327 |
327 |
{
|
|
328 |
Console.WriteLine("received GET request");
|
|
329 |
|
328 |
330 |
HttpListenerResponse response = context.Response;
|
329 |
331 |
response.AddHeader("Access-Control-Allow-Credentials", "true");
|
330 |
332 |
response.AddHeader("Access-Control-Expose-Headers", "ETag");
|
331 |
333 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
|
332 |
334 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
335 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
|
|
336 |
//response.AddHeader("Access-Control-Allow-Origin", "https://kacerekz.github.io/KIV-ASWI/");
|
333 |
337 |
response.AddHeader("Access-Control-Allow-Origin", "*");
|
334 |
338 |
|
|
339 |
|
|
340 |
|
335 |
341 |
//string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath;
|
336 |
342 |
// if (page == string.Empty)
|
337 |
343 |
// page = "test.txt";
|
... | ... | |
348 |
354 |
Stream st = response.OutputStream;
|
349 |
355 |
st.Write(buffer, 0, buffer.Length);
|
350 |
356 |
|
351 |
|
|
|
357 |
|
352 |
358 |
context.Response.Close();
|
353 |
359 |
}
|
354 |
360 |
|
355 |
361 |
else if (context.Request.HttpMethod == "POST") // when client says upload
|
356 |
362 |
{
|
|
363 |
Console.WriteLine("received POST request");
|
|
364 |
|
357 |
365 |
string text;
|
358 |
366 |
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
|
359 |
367 |
text = reader.ReadToEnd();
|
360 |
368 |
Console.WriteLine("Received request:");
|
361 |
369 |
Console.WriteLine(HttpUtility.UrlDecode(text));
|
362 |
370 |
|
363 |
|
context.Response.Close();
|
|
371 |
|
|
372 |
|
|
373 |
HttpListenerResponse response = context.Response;
|
|
374 |
response.AddHeader("Access-Control-Allow-Credentials", "true");
|
|
375 |
response.AddHeader("Access-Control-Expose-Headers", "ETag");
|
|
376 |
response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
|
|
377 |
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
378 |
response.AddHeader("Access-Control-Allow-Origin", "*");
|
|
379 |
|
|
380 |
|
|
381 |
|
|
382 |
int rand = new Random().Next(1, 10);
|
|
383 |
string msg = "OK " + rand;
|
|
384 |
|
|
385 |
byte[] buffer = Encoding.UTF8.GetBytes(msg);
|
|
386 |
|
|
387 |
response.ContentLength64 = buffer.Length;
|
|
388 |
Stream st = response.OutputStream;
|
|
389 |
st.Write(buffer, 0, buffer.Length);
|
|
390 |
|
|
391 |
|
|
392 |
context.Response.Close(); // ?? Works better with this, if this line is absent, the client gets 'stuck' after approximately 6 messages
|
|
393 |
}
|
|
394 |
else
|
|
395 |
{
|
|
396 |
Console.WriteLine("received request other than GET or POST");
|
|
397 |
Console.WriteLine("method: " + context.Request.HttpMethod);
|
|
398 |
Console.WriteLine("headers: " + context.Request.Headers);
|
|
399 |
Console.WriteLine("whole request?: " + context.Request);
|
|
400 |
Console.WriteLine("user: " + context.User);
|
|
401 |
|
|
402 |
|
|
403 |
|
|
404 |
//HttpListenerResponse response = context.Response;
|
|
405 |
//response.AddHeader("Access-Control-Allow-Credentials", "true");
|
|
406 |
//response.AddHeader("Access-Control-Expose-Headers", "ETag");
|
|
407 |
//response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time, Origin, Content-Type, X-Auth-Token");
|
|
408 |
//response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
409 |
//response.AddHeader("Access-Control-Allow-Origin", "*");
|
|
410 |
|
|
411 |
//string msg = "Preflight check? ";
|
|
412 |
|
|
413 |
//byte[] buffer = Encoding.UTF8.GetBytes(msg);
|
|
414 |
|
|
415 |
//response.ContentLength64 = buffer.Length;
|
|
416 |
//Stream st = response.OutputStream;
|
|
417 |
//st.Write(buffer, 0, buffer.Length);
|
|
418 |
|
|
419 |
|
|
420 |
//context.Response.Close(); // ??
|
|
421 |
|
364 |
422 |
}
|
365 |
423 |
}
|
366 |
424 |
}
|
... | ... | |
380 |
438 |
}
|
381 |
439 |
|
382 |
440 |
}
|
383 |
|
|
|
441 |
|
384 |
442 |
}
|
Re #8836. Fixed errors appearing when client sends POST request by sending an answer to the request.