-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimeOutSocketFactory.cs
112 lines (97 loc) · 3.4 KB
/
TimeOutSocketFactory.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
using CommsLIB.Helper;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace CommsLIB.Communications
{
public static class TimeOutSocketFactory
{
//public static TcpClient Connect1(IPEndPoint remoteEndPoint, int timeoutMSec)
//{
// TcpClient tcpclient = new TcpClient();
// int startTime = TimeTools.GetCoarseMillisNow();
// WaitHandle wh = null;
// try
// {
// IAsyncResult asyncResult = tcpclient.BeginConnect(remoteEndPoint.Address, remoteEndPoint.Port, null, null);
// wh = asyncResult.AsyncWaitHandle;
// if (wh.WaitOne(timeoutMSec, false))
// {
// tcpclient.EndConnect(asyncResult);
// if (tcpclient.Connected)
// return tcpclient;
// }
// }
// finally
// {
// wh?.Close();
// }
// // CLEAN
// try
// {
// tcpclient?.Dispose();
// }
// catch { }
// // See if we have to wait a little bit
// int wait = timeoutMSec - (TimeTools.GetCoarseMillisNow() - startTime);
// if (wait > 10)
// Thread.Sleep(wait);
// return null;
//}
public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
{
TcpClient tcpclient = new TcpClient();
int startTime = TimeTools.GetCoarseMillisNow();
try
{
IAsyncResult asyncResult = tcpclient.BeginConnect(remoteEndPoint.Address, remoteEndPoint.Port, null, null);
if (asyncResult.AsyncWaitHandle.WaitOne(timeoutMSec, false))
{
try
{
tcpclient.EndConnect(asyncResult);
return tcpclient;
}
catch
{
// See if we have to wait a little bit
int wait = timeoutMSec - (TimeTools.GetCoarseMillisNow() - startTime);
if (wait > 10)
Thread.Sleep(wait);
tcpclient?.Dispose();
return null;
}
}
else
{
// See if we have to wait a little bit
int wait = timeoutMSec - (TimeTools.GetCoarseMillisNow() - startTime);
if (wait > 10)
Thread.Sleep(wait);
try
{
tcpclient?.Dispose();
return null;
}
catch { }
return null;
}
} catch (Exception e)
{
// See if we have to wait a little bit
int wait = timeoutMSec - (TimeTools.GetCoarseMillisNow() - startTime);
if (wait > 10)
Thread.Sleep(wait);
try
{
tcpclient?.Dispose();
}
catch { }
return null;
}
}
}
}