-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTCPSocket.cs
1282 lines (1189 loc) · 30.5 KB
/
TCPSocket.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace OS.Communication
{
/// <summary>
/// Generic TCP/IP socket-based class is used across platforms
/// </summary>
public class TCPSocket : ICommunicationDevice
{
public override string ToString()
{
return $"{this.IPAddress}:{this.IPPort}";
}
public string DeviceName
{
get => this.ToString();
set { }
}
#region Event Sourcing
protected void FireStatusMessage(DeviceEventArgs SocketArgs)
{
this.FireCommunicationEvent(SocketArgs);
}
public event DeviceEvent CommunicationEvent;
#endregion
#region Properties
public bool AllowMultipleClientConnections { get; set; }
public ConnectMethods ConnectMethod
{
get
{
return this._ConnectMethod;
}
set
{
if (this._ConnectMethod == ConnectMethods.Undefined)
{
this._ConnectMethod = value;
}
}
}
protected ConnectMethods _ConnectMethod = ConnectMethods.Undefined;
public string MessageString { get; set; }
/// <summary>
/// Used to keep a reference of the async callback
/// </summary>
private AsyncCallback _AsyncCallback = null;
public class _InputData
{
public byte[] _InputBuffer;
public int position;
public int count;
public _InputData()
{
Initialize();
}
public void Initialize()
{
_InputBuffer = new byte[1024];
position = 0;
count = 0;
}
public void Clear()
{
this._InputBuffer.Initialize();
this.position = 0;
count = 0;
}
};
protected _InputData InputData = new _InputData();
protected IAsyncResult _ConnectAsyncResult = null;
public IAsyncResult ConnectAsyncResult
{
get
{
return this._ConnectAsyncResult;
}
}
protected IAsyncResult _ReadAsyncResult = null;
public IAsyncResult ReadAsyncResult
{
get
{
return this._ReadAsyncResult;
}
set
{
this._ReadAsyncResult = value;
}
}
protected IAsyncResult _WriteAsyncResult = null;
public IAsyncResult WriteAsyncResult
{
get
{
return this._WriteAsyncResult;
}
}
protected bool _IsListening = false;
public bool IsListening
{
get
{
if (this.mainSocket == null)
{
return false;
}
if (this.ConnectMethod == ConnectMethods.Client)
{
return false;
}
return this._IsListening;
}
}
protected StateObject MainSocketState = new StateObject();
// Points to the last socket that sent a message
protected DateTime CurrentTime = DateTime.Now;
protected string hostDescriptor = "";
public string HostDescriptor
{
get
{
if (this.mainSocket.Connected == true)
{
return this.mainSocket.RemoteEndPoint.ToString();
}
else
{
return "No Connection";
}
}
}
/// <summary>
/// The port number and 'key' for the hashtable containing all connected sockets
/// </summary>
protected int curSocketKey = -1;
protected Hashtable connectedClients = new Hashtable(10);
public int ListenerClientCount
{
get
{
lock (ClientLock)
{
return this.connectedClients.Count;
}
}
}
public Socket FirstConnectedSocket
{
get
{
Socket retSock = null;
lock (ClientLock)
{
foreach (DictionaryEntry de in this.connectedClients)
{
retSock = ((ClientSocketObject)de.Value).socket;
}
}
return retSock;
}
}
protected Socket mainSocket = null;
protected ManualResetEvent connectDone = new ManualResetEvent(false);
protected ManualResetEvent sendDone = new ManualResetEvent(false);
protected ManualResetEvent receiveDone = new ManualResetEvent(false);
public ManualResetEvent allDone = new ManualResetEvent(false);
protected string _IPAddress = "";
// [XmlIgnoreAttribute()]
public string IPAddress
{
get
{
return this._IPAddress;
}
set
{
this._IPAddress = value;
}
}
protected int _IPPort = 0;
// [XmlIgnoreAttribute()]
public int IPPort
{
get
{
return this._IPPort;
}
set
{
this._IPPort = value;
}
}
protected bool fSocketIsClosing = false;
public bool Listen = false;
// [XmlIgnoreAttribute()]
public int SendTimeout
{
get
{
if (this.mainSocket != null)
{
return (int)this.mainSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
}
return -1;
}
set
{
if (value >= 0)
{
if (this.mainSocket != null)
{
this.mainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)value);
}
}
}
}
// [XmlIgnoreAttribute()]
public int ReceiveTimeout
{
get
{
if (this.mainSocket != null)
{
return (int)this.mainSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
}
return -1;
}
set
{
if (value >= 0)
{
if (this.mainSocket != null)
{
this.mainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)value);
}
}
}
}
#endregion
#region Methods
// Copy Constructor
public TCPSocket()
{
this.Initialize();
// Create the TCP/IP socket.
this.mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}
public TCPSocket(ConnectMethods sockMethod)
{
this._ConnectMethod = (sockMethod);
// Create the TCP/IP socket.
this.mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}
public TCPSocket(int HostPort)
{
this._ConnectMethod = ConnectMethods.Listener;
this._IPPort = HostPort;
if (this._IPPort == 0)
{
this.MessageString = "An invalid port value was passed";
using (DeviceEventArgs evt = new DeviceEventArgs())
{
evt.Event = CommunicationEvents.Error;
evt.Description = this.MessageString;
FireStatusMessage(evt);
}
return;
}
this.mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}
public TCPSocket(string hostname, int port, ConnectMethods sockMethod)
{
this._ConnectMethod = sockMethod;
bool initError = false;
if ((hostname == null) || (hostname.Length == 0))
{
this.MessageString = "An invalid host address was passed for the client connection.";
initError = true;
}
if (port < 1)
{
this.MessageString = "An invalid host port was passed for the client connection.";
initError = true;
}
if (initError == true)
{
using (DeviceEventArgs evt = new DeviceEventArgs())
{
evt.Event = CommunicationEvents.Error;
evt.Description = this.MessageString;
FireStatusMessage(evt);
}
return;
}
this._IPAddress = hostname;
this._IPPort = port;
// Create the TCP/IP socket.
this.mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
this.mainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
}
public TCPSocket(Socket socket)
{
this._ConnectMethod = ConnectMethods.Client;
//this._IPAddress = socket.RemoteEndPoint.hostname;
//this._IPPort = port;
// Create the TCP/IP socket.
this.mainSocket = socket;
// assuming that the socket exists, is connected ...so, we just want to hear about it
if (this.MainSocket != null)
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = this.MainSocket;
this._ReadAsyncResult = this.MainSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
protected void FireCommunicationEvent(DeviceEventArgs e)
{
if (this.CommunicationEvent != null)
{
CommunicationEvent(this, e);
}
}
public Socket GetConnectedSocket(IntPtr handle)
{
lock (ClientLock)
{
foreach (DictionaryEntry de in this.connectedClients)
{
if (((ClientSocketObject)de.Value).socket.Handle == handle)
{
return ((ClientSocketObject)de.Value).socket;
}
}
}
return null;
}
public Socket GetConnectedSocket(int port)
{
// the port number is used as the 'key' to the hashtable values
lock (ClientLock)
{
if (this.connectedClients.ContainsKey(port) == false) return null;
return ((ClientSocketObject)this.connectedClients[port]).socket;
}
}
/// <summary>
/// This function is designed to nest within an infinite loop to provide
/// a means to exit, or timeout.
/// </summary>
/// <param name="counter"></param>
/// <param name="limit"></param>
/// <param name="sleepInterval"></param>
/// <returns></returns>
protected bool StepLoop(ref int counter, int limit, int sleepInterval)
{
System.Threading.Thread.Sleep(sleepInterval);
//Application.DoEvents();
if (counter++ > limit)
{
return false;
}
return true;
}
/// <summary>
/// This function runs a synchronous loopback test. Usually used with serial-to-ethernet
/// servers/clients equipped with a loopback connector.
/// </summary>
/// <returns></returns>
public bool RunSyncLoopBackTest()
{
int tCounter = 0;
this.ConnectMethod = ConnectMethods.Client;
if (this.IsConnected == true)
{
this.Close();
tCounter = 0;
while (this.ReadAsyncResult == null)
{
if (this.StepLoop(ref tCounter, 100, 10) == false)
{
return false;
}
}
tCounter = 0;
while (this.ReadAsyncResult.IsCompleted != true)
{
if (this.StepLoop(ref tCounter, 100, 10) == false)
{
return false;
}
}
tCounter = 0;
while (this.IsConnected == true)
{
if (this.StepLoop(ref tCounter, 100, 10) == false)
{
return false;
}
}
}
this.Open();
tCounter = 0;
while (this.ConnectAsyncResult == null)
{
if (this.StepLoop(ref tCounter, 100, 10) == false)
{
return false;
}
}
tCounter = 0;
while (this.ConnectAsyncResult.IsCompleted != true)
{
if (this.StepLoop(ref tCounter, 100, 10) == false)
{
return false;
}
}
if (this.mainSocket.Connected == false)
{
return false;
}
byte[] testData = new byte[256];
byte[] rcvData = new byte[1];
int i = 0;
for (i = 0; i < 256; i++)
{
testData[i] = (byte)i;
}
try
{
for (i = 0; i < 5; i++)
{
this.mainSocket.Send(testData, 0, 1, SocketFlags.None);
this.receiveDone.Reset();
this.receiveDone.WaitOne();
this.Read(rcvData, 0, rcvData.Length);
// this.mainSocket.Receive(testData,0,1,SocketFlags.None);
if (rcvData[0] != testData[i])
{
return true;
}
}
}
catch (Exception)
{
//MessageBox.Show("Error: " + ex.Message,"Loopback Test",MessageBoxButtons.OK,
// MessageBoxIcon.Error);
return false;
}
return true;
}
private bool StartListening()
{
if (this._IPPort == 0)
{
return false;
}
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(System.Net.IPAddress.Any, this._IPPort);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
this.mainSocket.Bind(localEndPoint);
this.mainSocket.Listen(0);
Listen = true;
// while (Listen == true)
// {
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
using (DeviceEventArgs sk = new DeviceEventArgs())
{
this.mainSocket.BeginAccept(new AsyncCallback(AcceptCallback),
this.mainSocket);
// The socket is considered as listening at this point
this._IsListening = true;
sk.Event = CommunicationEvents.Listening;
FireStatusMessage(sk);
}
// Wait until a connection is made before continuing.
// allDone.WaitOne();
// }
}
catch (SocketException ex)
{
this._IsListening = false;
using (DeviceEventArgs sk = new DeviceEventArgs())
{
sk.Event = CommunicationEvents.Error;
sk.Description = ex.Message;
this.MessageString = ex.Message;
FireStatusMessage(sk);
}
return false;
}
catch (Exception ex)
{
this._IsListening = false;
this.MessageString = ex.Message;
using (DeviceEventArgs sk = new DeviceEventArgs())
{
sk.Event = CommunicationEvents.Error;
sk.Description = ex.Message;
FireStatusMessage(sk);
}
return false;
}
return true;
}
public void AcceptCallback(IAsyncResult ar)
{
ClientSocketObject socketObject = null;
using (DeviceEventArgs sk = new DeviceEventArgs())
{
if (this.fSocketIsClosing == true)
{
this.fSocketIsClosing = false;
sk.Event = CommunicationEvents.Disconnected;
FireStatusMessage(sk);
return;
}
// Signal the main thread to continue.
// allDone.Set();
Socket listener = null;
int port = 0;
try
{
// Get the socket that handles the client request.
listener = (Socket)ar.AsyncState;
// Then, get the new client socket
socketObject = new ClientSocketObject();
if (((Socket)listener).Handle.ToInt32() == -1)
{
return;
}
socketObject.socket = (Socket)listener.EndAccept(ar);
// Return if only one client is intended to communicate
if (!this.AllowMultipleClientConnections && this.connectedClients.Count > 0)
{
socketObject.socket.Close();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
return;
}
port = ((System.Net.IPEndPoint)socketObject.socket.RemoteEndPoint).Port;
// Save the port (as key) and socket object (as value) in our hashtable
lock (ClientLock)
{
this.connectedClients.Add(port, socketObject);
}
}
catch (Exception ex)
{
this.MessageString = ex.Message;
sk.Event = CommunicationEvents.Error;
FireStatusMessage(sk);
return;
}
try
{
this.curSocketKey = port;
lock (ClientLock)
{
// Create the state object.
((ClientSocketObject)connectedClients[port]).state = new StateObject();
// StateObject state = new StateObject();
((ClientSocketObject)connectedClients[port]).state.workSocket = ((ClientSocketObject)connectedClients[port]).socket;
// DON'T START A BEGINRECEIVE OPERATION HERE...THIS IS THE LISTENER - TAKING NEW CLIENTS
// LET THE HOST APP GET DATA FROM ICommunicationDevice EVENTS ACCESSIBLE IN THE EVENT BELOW
// THE HOST APP WILL DEAL WITH THE CLIENTS - AND THEIR RESPECTIVE EVENTS
//this._ReadAsyncResult = ((clientSocketObject)connectedClients[port]).socket.BeginReceive(((clientSocketObject)connectedClients[port]).state.buffer, 0, StateObject.BufferSize, 0,
// new AsyncCallback(ReceiveCallback), ((clientSocketObject)connectedClients[port]).state);
}
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
lock (ClientLock)
{
sk.Event = CommunicationEvents.ClientConnected;
sk.Description = ((ClientSocketObject)connectedClients[port]).socket.RemoteEndPoint.ToString(); ;
//sk.socketHandler = ((ClientSocketObject)connectedClients[port]).socket;
sk.dataObject = port;
// Offer a reference to the connected client as an 'ICommunicationDevice'
sk.dataObject1 = new TCPSocket(((ClientSocketObject)connectedClients[port]).socket);
FireStatusMessage(sk);
}
}
catch (Exception ex)
{
this.MessageString = ex.Message;
sk.Event = CommunicationEvents.Error;
FireStatusMessage(sk);
return;
}
}
}
public byte[] Read()
{
return new byte[] { };
}
private object ClientLock = new object();
public void ReceiveCallback(IAsyncResult ar)
{
DeviceEventArgs sk = new DeviceEventArgs();
String content = String.Empty;
if (this.fSocketIsClosing == true)
{
this.fSocketIsClosing = false;
sk.Description = "Connection Closed";
sk.Event = CommunicationEvents.Disconnected;
FireStatusMessage(sk);
return;
}
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = null;
Socket sck = null;
state = (StateObject)ar.AsyncState;
sck = state.workSocket;
int portKey = 0; // serves as the socket port and the hashtable key
if (this.ConnectMethod == ConnectMethods.Listener)
{
lock (this.ClientLock)
{
if (this.connectedClients.Count > 0)
{
foreach (DictionaryEntry de in this.connectedClients)
{
if (((ClientSocketObject)de.Value).socket.Handle == sck.Handle)
{
this.curSocketKey = portKey = (int)de.Key;
break;
}
}
}
}
}
else
{
// Only do this in the case of a client where 'MainSocket' is the only socket
this.MainSocketState = (StateObject)ar.AsyncState;
this.MainSocketState.workSocket = state.workSocket;
}
int bytesRead = 0;
try
{
// Read data from the client socket.
if (sck != null)
{
// Take a look at the endpoint's ip address - if its string representation is
// zero length then it's considered disconnected
if ((sck.Connected == true) && (sck.Handle.ToInt32() != -1))
{
if (sck.Poll(50, SelectMode.SelectError) == false)
{
bytesRead = sck.EndReceive(ar);
// this._ReadAsyncResult = null;
}
}
}
}
catch (SocketException ex)
{
string txt;
if (ex.ErrorCode == 10014)
{
txt = "The host at address " + ((IPEndPoint)sck.RemoteEndPoint).Address.ToString()
+ " has unexpectedly disconnected.";
}
else
{
txt = ex.Message;
}
txt += " - Error Code: " + Convert.ToString(ex.ErrorCode);
this.MessageString = txt;
sk.Event = CommunicationEvents.Error;
sk.Description = txt;
FireStatusMessage(sk);
}
catch (ObjectDisposedException ex)
{
this.MessageString = ex.Message;
sk.Event = CommunicationEvents.Error;
sk.Description = ex.Message;
FireStatusMessage(sk);
}
catch (Exception ex)
{
this.MessageString = ex.Message;
sk.Event = CommunicationEvents.Error;
sk.Description = ex.Message;
FireStatusMessage(sk);
}
if (bytesRead > 0)
{
// Move the byte data into the local input buffer
for (int i = 0; i < bytesRead; i++)
{
this.InputData._InputBuffer[this.InputData.position + i] = state.buffer[i];
}
this.InputData.position += bytesRead;
this.InputData.count += bytesRead;
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Did we get all of the expected data at this point ?
try
{
// *************END RECEIVE EVENT**********************
using (DeviceEventArgs evt = new DeviceEventArgs())
{
evt.data = new byte[(int)this.InputData.count];
for (int i = 0; i < this.InputData.count; i++)
{
evt.data[i] = this.InputData._InputBuffer[i];
}
this.InputData.Clear();
evt.dataObject = sck;
evt.Event = CommunicationEvents.ReceiveEnd;
evt.Description = content;
FireStatusMessage(evt);
}
state.sb.Remove(0, state.sb.ToString().Length);
}
catch (Exception ex)
{
state.sb.Remove(0, state.sb.ToString().Length);
this.MessageString = "RcvCallback - " + ex.Message;
}
try
{
if (this._ConnectMethod == ConnectMethods.Listener)
{
lock (ClientLock)
{
if (this.connectedClients.Count > 0)
{
this._ReadAsyncResult = ((ClientSocketObject)this.connectedClients[portKey]).socket.BeginReceive(
state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
}
else
{
this._ReadAsyncResult = sck.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
catch (Exception)
{
}
}
else // No bytes - Remote Disconnect
{
using (DeviceEventArgs evt = new DeviceEventArgs())
{
sck.Close();
evt.Event = CommunicationEvents.RemoteDisconnect;
lock (ClientLock)
{
if (this.connectedClients.Count > 0)
{
this.connectedClients.Remove(portKey);
}
}
// Keep on listening if we're not closing, and we are a server
if ((this.fSocketIsClosing == false) && (this._ConnectMethod == ConnectMethods.Listener))
{
try
{
if (this.mainSocket != null)
{
this.mainSocket.BeginAccept(new AsyncCallback(AcceptCallback),
this.mainSocket);
}
}
catch (Exception e)
{
this.MessageString = e.Message;
}
}
else
{
evt.Event = CommunicationEvents.Disconnected;
}
evt.dataObject = this.curSocketKey; // indicate which port remotely disconnected
FireStatusMessage(evt);
}
}
}
public Socket MainSocket
{
get
{
return this.mainSocket;
}
}
/// <summary>
/// It is important that all notifications route through this function
/// </summary>
/// <param name="SocketArgs"></param>
protected void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
if (client == null)
{
return;
}
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
// this._WriteAsyncResult = null;
//Console.WriteLine("Sent {0} bytes.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private bool StartClient()
{
this.ConnectTimedOut = false;
try // Connect to a remote device.
{
IPEndPoint remoteEP = new IPEndPoint(System.Net.IPAddress.Parse(this.IPAddress)
, this._IPPort);
// Connect to the remote endpoint.
this._AsyncCallback = new AsyncCallback(ConnectCallback);
this._ConnectAsyncResult = this.mainSocket.BeginConnect(remoteEP,
this._AsyncCallback, this.mainSocket);
connectDone.Reset();
bool success = this._ConnectAsyncResult.AsyncWaitHandle.WaitOne(8000, true);
if (!this.mainSocket.Connected)
{
if (!success)
{
this.mainSocket.Close();
//this.mainSocket.Dispose();
this.ConnectTimedOut = true;
this.FireCommunicationEvent(new DeviceEventArgs()
{
Event = CommunicationEvents.Error,
Description = "WiFi Connect Timeout",
});
}
}
}
catch (Exception e)
{
using (DeviceEventArgs evt = new DeviceEventArgs())
{
evt.Event = CommunicationEvents.Error;
evt.Description = e.Message;
this.MessageString = e.Message;
FireStatusMessage(evt);
return false;
}
}
FireCommunicationEvent(new DeviceEventArgs()
{
Event = CommunicationEvents.ClientConnected,
Description = "Connected"
});
return true;
}
private bool ConnectTimedOut = false;
protected void ConnectCallback(IAsyncResult ar)
{
using (DeviceEventArgs evt = new DeviceEventArgs())
{
Socket sck = null;
try
{
if (this.ConnectTimedOut) return;
// Retrieve the socket from the state object.
sck = (Socket)ar.AsyncState;
// Complete the connect action.
sck.EndConnect(ar);
Console.WriteLine($"Socket connected to {sck.RemoteEndPoint.ToString()}");
// Signal that the connection action has completed.
evt.Description = this.MainSocket.RemoteEndPoint.ToString();
evt.Event = CommunicationEvents.ConnectedAsClient;
}
catch (ObjectDisposedException ex)// usually, when the user closes before connection is resolved.
{
evt.Event = CommunicationEvents.Disconnected;
evt.Description = $"Error: {ex.Message}";
FireStatusMessage(evt);
return;
}
catch (Exception e)
{
evt.Event = CommunicationEvents.Error;
evt.Description = e.Message;
FireStatusMessage(evt);
return;
}
finally
{
connectDone.Set();
}
if (sck != null && sck.Connected)
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = sck;
this._ReadAsyncResult = sck.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
FireStatusMessage(evt);
}
}