-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathConnectionPool.cs
111 lines (92 loc) · 3.01 KB
/
ConnectionPool.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
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using SmileGatewayCore.Exception;
namespace SmileGatewayCore.Instance.Upstream;
// 연결 관리는 어떻게?
internal class ConnectionPool
{
// 서버가 죽어있을 때는 어떻게 체크할 것인가?
public int Capacity { get; private set; }
private ConcurrentQueue<Socket> _sockets = new ConcurrentQueue<Socket>();
private long count = 0;
public long AliveCount { get => Interlocked.Read(ref count); }
public void EnqueueSocket(Socket socket) { _sockets.Enqueue(socket); }
public ConnectionPool(int capacity)
{
Capacity = capacity;
}
public async Task Init(IPEndPoint endPoint, TimeSpan timeout)
{
for (int i = 0; i < Capacity; i++)
{
// 설정 통해서 커넥션 유지
Socket socket = CreateSocket();
try
{
await ConnectAsync(socket, endPoint, timeout);
EnqueueSocket(socket);
AddAliveCount();
}
catch (System.Exception e)
{
System.Console.WriteLine(e.Message);
}
}
}
public async Task<Socket?> GetSocket(IPEndPoint endPoint, TimeSpan timeout)
{
if (_sockets.TryDequeue(out Socket? socket))
{
return socket;
}
else
{
return await MakeConnectSocket(endPoint, timeout);
}
}
public void AddAliveCount()
{
if (Interlocked.CompareExchange(ref count, Capacity, Capacity) <= Capacity)
Interlocked.Increment(ref count);
}
public void MinusAliveCount()
{
if (Interlocked.CompareExchange(ref count, 0, 0) > 0)
Interlocked.Decrement(ref count);
}
public Socket CreateSocket()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
return socket;
}
public async Task ConnectAsync(Socket socket, IPEndPoint endPoint, TimeSpan timout)
{
var connectTask = socket.ConnectAsync(endPoint);
var timerTask = Task.Delay(timout);
var completedTask = await Task.WhenAny(timerTask, connectTask);
if (completedTask == timerTask)
throw new TimeoutException();
if (socket.Connected == false)
throw new NetworkException(3200);
}
public async Task<Socket?> MakeConnectSocket(IPEndPoint endPoint, TimeSpan timeout)
{
Socket socket = CreateSocket();
try
{
if (AliveCount >= Capacity)
return null;
await ConnectAsync(socket, endPoint, timeout);
AddAliveCount();
return socket;
}
catch
{
socket.Dispose();
}
return null;
}
}