-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketStable.cs
82 lines (73 loc) · 2.21 KB
/
SocketStable.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
using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Redecode.Archimede
{
public class SocketStable
{
public static Socket Connect(string ip, int port, int timeout = 5000)
{
bool connected = false;
int millsConnect = 0;
int millsThread = 0;
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
Socket socket = null;
do
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Thread tConnect = new Thread(() =>
{
try
{
socket.Connect(endPoint);
connected = true;
}
catch
{
return;
}
});
tConnect.Start();
//--- tConnect.Join(1000); <--- it does't work if it's in a Timer callback. Solved with while() below
millsThread = 0;
while (tConnect.IsAlive && millsThread < 1000)
{
Thread.Sleep(10);
millsThread += 10;
}
if (tConnect.IsAlive)
{
tConnect.Abort();
}
}
catch
{
}
finally
{
if (!connected)
{
if (socket != null)
{
socket.Close();
}
millsConnect += 1000;
connected = false;
}
}
} while (!connected && millsConnect < timeout);
if (connected)
{
return socket;
}
else
{
return null;
}
}
}
}