1 |
|
using System;
|
2 |
|
using System.Collections.Generic;
|
3 |
|
using System.Linq;
|
|
1 |
//
|
|
2 |
// Author: Eliska Mourycova
|
|
3 |
//
|
|
4 |
|
|
5 |
using System;
|
4 |
6 |
using System.Net;
|
5 |
7 |
using System.Net.Sockets;
|
6 |
8 |
using System.Text;
|
7 |
9 |
using System.Threading;
|
8 |
|
using System.Threading.Tasks;
|
9 |
10 |
|
10 |
11 |
namespace Connection
|
11 |
12 |
{
|
12 |
|
// State object for reading client data asynchronously
|
|
13 |
/// <summary>
|
|
14 |
/// State object for reading client data asynchronously
|
|
15 |
/// </summary>
|
13 |
16 |
public class StateObject
|
14 |
17 |
{
|
15 |
18 |
// Client socket.
|
16 |
|
public Socket workSocket = null;
|
|
19 |
public Socket WorkSocket = null;
|
17 |
20 |
// Size of receive buffer.
|
18 |
|
public const int BufferSize = 1024;
|
|
21 |
public const int BUFFER_SIZE = 1024;
|
19 |
22 |
// Receive buffer.
|
20 |
|
public byte[] buffer = new byte[BufferSize];
|
|
23 |
public byte[] Buffer = new byte[BUFFER_SIZE];
|
21 |
24 |
// Received data string.
|
22 |
|
public StringBuilder sb = new StringBuilder();
|
|
25 |
public StringBuilder StrBuilder = new StringBuilder();
|
23 |
26 |
}
|
24 |
27 |
|
|
28 |
/// <summary>
|
|
29 |
/// This class takes care of client connection. It serves clients asynchronously.
|
|
30 |
/// </summary>
|
25 |
31 |
public class AsynchronousSocketListener
|
26 |
32 |
{
|
27 |
|
// Thread signal.
|
28 |
|
public static ManualResetEvent allDone = new ManualResetEvent(false);
|
|
33 |
// port numbers:
|
|
34 |
private const int PORT_NO = 11000;
|
|
35 |
private const int ADMIN_PORT_NO = 10000;
|
29 |
36 |
|
30 |
|
public AsynchronousSocketListener()
|
31 |
|
{
|
32 |
|
}
|
33 |
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>
|
34 |
44 |
public void StartListening()
|
35 |
45 |
{
|
36 |
46 |
// Data buffer for incoming data.
|
37 |
47 |
byte[] bytes = new Byte[1024];
|
38 |
48 |
|
39 |
|
// Establish the local endpoint for the socket.
|
40 |
|
// The DNS name of the computer
|
41 |
|
// running the listener is "host.contoso.com".
|
|
49 |
// Establish the local endpoint for the socket:
|
42 |
50 |
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
|
|
51 |
|
|
52 |
// Get the IP of the machine - UNUSED ATM, USING LOOPBACK ON LOCALHOST
|
43 |
53 |
IPAddress ipAddress = ipHostInfo.AddressList[1];
|
44 |
|
Console.WriteLine("ip: " + ipAddress.ToString());
|
45 |
|
IPEndPoint localEndPoint = new IPEndPoint(/*ipAddress*/IPAddress.Loopback, 11000);
|
|
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);
|
46 |
57 |
|
47 |
58 |
// Create a TCP/IP socket.
|
48 |
|
Socket listener = new Socket(AddressFamily.InterNetwork,
|
49 |
|
SocketType.Stream, ProtocolType.Tcp);
|
|
59 |
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
60 |
Socket listenerAdmin = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
50 |
61 |
|
51 |
62 |
// Bind the socket to the local endpoint and listen for incoming connections.
|
52 |
63 |
try
|
... | ... | |
54 |
65 |
listener.Bind(localEndPoint);
|
55 |
66 |
listener.Listen(100);
|
56 |
67 |
|
|
68 |
listenerAdmin.Bind(localEndPointAdmin);
|
|
69 |
listenerAdmin.Listen(1);
|
|
70 |
|
|
71 |
// keep accepting
|
57 |
72 |
while (true)
|
58 |
73 |
{
|
59 |
74 |
// Set the event to nonsignaled state.
|
... | ... | |
62 |
77 |
// Start an asynchronous socket to listen for connections.
|
63 |
78 |
Console.WriteLine("Waiting for a connection...");
|
64 |
79 |
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
|
|
80 |
listenerAdmin.BeginAccept(new AsyncCallback(AcceptCallback), listenerAdmin);
|
65 |
81 |
|
66 |
82 |
// Wait until a connection is made before continuing.
|
67 |
83 |
allDone.WaitOne();
|
... | ... | |
70 |
86 |
}
|
71 |
87 |
catch (Exception e)
|
72 |
88 |
{
|
|
89 |
// bind failed
|
73 |
90 |
Console.WriteLine(e.ToString());
|
74 |
91 |
}
|
75 |
92 |
|
... | ... | |
78 |
95 |
|
79 |
96 |
}
|
80 |
97 |
|
81 |
|
public void AcceptCallback(IAsyncResult ar)
|
|
98 |
// Routine for when BeginAccept on the given listener ended
|
|
99 |
private void AcceptCallback(IAsyncResult ar)
|
82 |
100 |
{
|
83 |
101 |
// Signal the main thread to continue.
|
84 |
102 |
allDone.Set();
|
85 |
103 |
Console.WriteLine("Accepted a connection.");
|
|
104 |
|
86 |
105 |
|
87 |
106 |
// Get the socket that handles the client request.
|
88 |
107 |
Socket listener = (Socket)ar.AsyncState;
|
89 |
108 |
Socket handler = listener.EndAccept(ar);
|
90 |
109 |
|
|
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());
|
|
114 |
|
|
115 |
|
|
116 |
|
|
117 |
|
91 |
118 |
// Create the state object.
|
92 |
119 |
StateObject state = new StateObject();
|
93 |
|
state.workSocket = handler;
|
94 |
|
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
|
|
120 |
state.WorkSocket = handler;
|
|
121 |
handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state);
|
95 |
122 |
|
96 |
123 |
}
|
97 |
124 |
|
98 |
|
public void ReadCallback(IAsyncResult ar)
|
|
125 |
// Routine for when BeginReceive on the given listener ended
|
|
126 |
private void ReadCallback(IAsyncResult ar)
|
99 |
127 |
{
|
100 |
|
|
101 |
|
|
102 |
|
|
103 |
|
|
|
128 |
// string for the received message
|
104 |
129 |
String content = String.Empty;
|
105 |
130 |
|
106 |
131 |
// Retrieve the state object and the handler socket
|
107 |
132 |
// from the asynchronous state object.
|
108 |
133 |
StateObject state = (StateObject)ar.AsyncState;
|
109 |
|
Socket handler = state.workSocket;
|
|
134 |
Socket handler = state.WorkSocket;
|
110 |
135 |
|
|
136 |
// check if we're still connected
|
111 |
137 |
if (!SocketConnected(handler))
|
112 |
138 |
{
|
|
139 |
// if the client isn't connected anymore, take care of cleanup
|
113 |
140 |
Console.WriteLine("Closing connection - unexpected...");
|
114 |
141 |
CloseConnection(handler);
|
|
142 |
|
|
143 |
// return so that we don't attempt to read from a non-existent stream
|
115 |
144 |
return;
|
116 |
145 |
}
|
117 |
146 |
|
118 |
|
// Read data from the client socket.
|
|
147 |
// check if it is admin's request we're serving
|
|
148 |
bool admin = ((IPEndPoint)handler.LocalEndPoint).Port == ADMIN_PORT_NO;
|
|
149 |
|
|
150 |
// Read data from the client socket.
|
119 |
151 |
int bytesRead = handler.EndReceive(ar);
|
120 |
152 |
|
121 |
153 |
if (bytesRead > 0)
|
122 |
154 |
{
|
123 |
155 |
// There might be more data, so store the data received so far.
|
124 |
|
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
|
|
156 |
state.StrBuilder.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead));
|
125 |
157 |
|
126 |
|
// Check for end-of-file tag. If it is not there, read
|
127 |
|
// more data.
|
128 |
|
content = state.sb.ToString();
|
|
158 |
// Check for end-of-file tag. If it is not there, read more data.
|
|
159 |
content = state.StrBuilder.ToString();
|
129 |
160 |
if (content.IndexOf("!") > -1)
|
130 |
161 |
{
|
131 |
|
// All the data has been read from the
|
132 |
|
// client. Display it on the console.
|
|
162 |
// All the data has been read from the client. Display it on the console.
|
133 |
163 |
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
|
134 |
164 |
|
135 |
|
content = ParseMessageAndBuildAnswer(content);
|
|
165 |
// parse the message and determine the response:
|
|
166 |
content = ParseMessageAndBuildAnswer(content, admin);
|
|
167 |
|
|
168 |
// check if the client wishes to close the connection:
|
136 |
169 |
if (content.Equals("bye!"))
|
137 |
170 |
{
|
138 |
171 |
Console.WriteLine("Closing connection - expected...");
|
... | ... | |
142 |
175 |
return;
|
143 |
176 |
}
|
144 |
177 |
|
145 |
|
// Echo the data back to the client.
|
|
178 |
// Send a response to the client
|
146 |
179 |
Send(handler, content);
|
147 |
180 |
|
|
181 |
// clear the string
|
|
182 |
state.StrBuilder.Clear();
|
148 |
183 |
|
149 |
|
state.sb.Clear();
|
150 |
|
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
|
|
184 |
// begin receiving another message:
|
|
185 |
handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state);
|
151 |
186 |
}
|
152 |
187 |
else
|
153 |
188 |
{
|
154 |
189 |
// Not all data received. Get more.
|
155 |
|
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
|
|
190 |
handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), state);
|
156 |
191 |
}
|
157 |
192 |
}
|
158 |
193 |
}
|
159 |
194 |
|
|
195 |
// Takes care of sending data to a connected client
|
160 |
196 |
private void Send(Socket handler, String data)
|
161 |
197 |
{
|
162 |
198 |
// Convert the string data to byte data using ASCII encoding.
|
... | ... | |
166 |
202 |
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
|
167 |
203 |
}
|
168 |
204 |
|
|
205 |
// Routine for when BeginSend on the given listener ended
|
169 |
206 |
private void SendCallback(IAsyncResult ar)
|
170 |
207 |
{
|
171 |
208 |
try
|
... | ... | |
184 |
221 |
}
|
185 |
222 |
catch (Exception e)
|
186 |
223 |
{
|
|
224 |
// close connection here?
|
|
225 |
|
187 |
226 |
Console.WriteLine(e.ToString());
|
188 |
227 |
}
|
189 |
228 |
}
|
190 |
229 |
|
191 |
230 |
|
192 |
|
|
193 |
|
|
194 |
|
|
195 |
|
|
196 |
|
|
197 |
|
private string ParseMessageAndBuildAnswer(string message)
|
|
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)
|
198 |
238 |
{
|
|
239 |
Console.WriteLine("Parsing message from admin: " + admin);
|
199 |
240 |
string ans = "";
|
200 |
241 |
|
201 |
242 |
if (message.Equals("hello!"))
|
... | ... | |
220 |
261 |
return ans;
|
221 |
262 |
}
|
222 |
263 |
|
223 |
|
|
|
264 |
/// <summary>
|
|
265 |
/// Closes the connection on the passed Socket
|
|
266 |
/// </summary>
|
|
267 |
/// <param name="s">The socket to close the connection for</param>
|
224 |
268 |
private void CloseConnection(Socket s)
|
225 |
269 |
{
|
226 |
270 |
s.Shutdown(SocketShutdown.Both);
|
227 |
271 |
s.Close();
|
228 |
272 |
}
|
229 |
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>
|
230 |
279 |
private bool SocketConnected(Socket s)
|
231 |
280 |
{
|
232 |
281 |
bool part1 = s.Poll(1000, SelectMode.SelectRead);
|
Refs #8620, #8619. Refactor + testing.