/
AsynchronousSocketListener.cs
261 lines (202 loc) · 8 KB
/
AsynchronousSocketListener.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace bd.tools.net
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class SocketListenerEventArgs : EventArgs
{
public const string MESSAGE_RECEIVED = "message_received";
public const string SERVER_STERTED = "server_started";
public string type { get; set; }
public string data { get; set; }
public DateTime TimeReached { get; set; }
}
public class AsynchronousSocketListener
{
public delegate void SocketListenerEventHandler(Object sender, SocketListenerEventArgs e);
public event SocketListenerEventHandler SocketEvent;
// Thread signal.
private ManualResetEvent allDone = new ManualResetEvent(false);
private Thread socetThread;
private string message = null;
private const int defaultPort = 11000;
public AsynchronousSocketListener()
{
}
public void Start()
{
// StartListening();
if (socetThread != null)
{
// throw new Exception("Server's already running!");
}
socetThread = new Thread(StartListening);
socetThread.Name = "SocetThread";
socetThread.IsBackground = true;
socetThread.Start();
}
public void NotifyUploadDone()
{
}
private void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
var host = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = null;
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip;
Console.WriteLine("ipadress "+ ipAddress);
}
}
if (ipAddress == null)
{
Console.WriteLine("Local IP adress not found");
return;
}
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
Console.WriteLine("Socket oppended at:{0}:{1}", localEndPoint.Address.ToString(), AsynchronousSocketListener.defaultPort);
NotifyServerStart(localEndPoint.Address.ToString() + ":" + AsynchronousSocketListener.defaultPort);
while (true)
{
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
/// Console.WriteLine("\nPress ENTER to continue...");
// Console.Read();
}
private void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
private void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
// Echo the data back to the client.
///
NotifyMessageReceived(content);
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private void NotifyMessageReceived(string data)
{
SocketListenerEventArgs args = new SocketListenerEventArgs();
args.type = SocketListenerEventArgs.MESSAGE_RECEIVED;
args.data = data;
args.TimeReached = new DateTime();
if (SocketEvent != null)
{
SocketEvent(this, args);
}
}
private void NotifyServerStart(string data)
{
SocketListenerEventArgs args = new SocketListenerEventArgs();
args.type = SocketListenerEventArgs.SERVER_STERTED;
args.data = data;
args.TimeReached = new DateTime();
if (SocketEvent != null)
{
SocketEvent(this, args);
}
}
private void Send(Socket handler, String data)
{
allDone.Set();
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Send);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}