This repository has been archived by the owner on May 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketWrapper.cs
191 lines (163 loc) · 6.43 KB
/
SocketWrapper.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
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;
namespace Fleck
{
public class SocketWrapper : ISocket
{
public const UInt32 KeepAliveInterval = 60000;
public const UInt32 RetryInterval = 10000;
private readonly Socket _socket;
private Stream _stream;
private CancellationTokenSource _tokenSource;
private TaskFactory _taskFactory;
public string RemoteIpAddress
{
get
{
var endpoint = _socket.RemoteEndPoint as IPEndPoint;
return endpoint != null ? endpoint.Address.ToString() : null;
}
}
public int RemotePort
{
get
{
var endpoint = _socket.RemoteEndPoint as IPEndPoint;
return endpoint != null ? endpoint.Port : -1;
}
}
public void SetKeepAlive(Socket socket, UInt32 keepAliveInterval, UInt32 retryInterval)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
int size = sizeof(UInt32);
UInt32 on = 1;
byte[] inArray = new byte[size * 3];
Array.Copy(BitConverter.GetBytes(on), 0, inArray, 0, size);
Array.Copy(BitConverter.GetBytes(keepAliveInterval), 0, inArray, size, size);
Array.Copy(BitConverter.GetBytes(retryInterval), 0, inArray, size * 2, size);
socket.IOControl(IOControlCode.KeepAliveValues, inArray, null);
}
}
public SocketWrapper(Socket socket)
{
_tokenSource = new CancellationTokenSource();
_taskFactory = new TaskFactory(_tokenSource.Token);
_socket = socket;
if (_socket.Connected)
_stream = new NetworkStream(_socket);
// The tcp keepalive default values on most systems
// are huge (~7200s). Set them to something more reasonable.
SetKeepAlive(socket, KeepAliveInterval, RetryInterval);
}
public Task Authenticate(X509Certificate2 certificate, SslProtocols enabledSslProtocols, Action callback, Action<Exception> error)
{
var ssl = new SslStream(_stream, false);
_stream = new QueuedStream(ssl);
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, enabledSslProtocols, false, cb, s);
Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null);
task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
return task;
}
public void Listen(int backlog)
{
_socket.Listen(backlog);
}
public void Bind(EndPoint endPoint)
{
_socket.Bind(endPoint);
}
public bool Connected
{
get { return _socket.Connected; }
}
public Stream Stream
{
get { return _stream; }
}
public bool NoDelay
{
get { return _socket.NoDelay; }
set { _socket.NoDelay = value; }
}
public EndPoint LocalEndPoint
{
get { return _socket.LocalEndPoint; }
}
public Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset)
{
try
{
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => _stream.BeginRead(buffer, offset, buffer.Length, cb, s);
Task<int> task = Task.Factory.FromAsync<int>(begin, _stream.EndRead, null);
task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted)
.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
return task;
}
catch (Exception e)
{
error(e);
return null;
}
}
public Task<ISocket> Accept(Action<ISocket> callback, Action<Exception> error)
{
Func<IAsyncResult, ISocket> end = r => _tokenSource.Token.IsCancellationRequested ? null : new SocketWrapper(_socket.EndAccept(r));
var task = _taskFactory.FromAsync(_socket.BeginAccept, end, null);
task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.OnlyOnRanToCompletion)
.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
return task;
}
public void Dispose()
{
_tokenSource.Cancel();
if (_stream != null) _stream.Dispose();
if (_socket != null) _socket.Dispose();
}
public void Close()
{
_tokenSource.Cancel();
if (_stream != null) _stream.Close();
if (_socket != null) _socket.Close();
}
public int EndSend(IAsyncResult asyncResult)
{
_stream.EndWrite(asyncResult);
return 0;
}
public Task Send(byte[] buffer, Action callback, Action<Exception> error)
{
if (_tokenSource.IsCancellationRequested)
return null;
try
{
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => _stream.BeginWrite(buffer, 0, buffer.Length, cb, s);
Task task = Task.Factory.FromAsync(begin, _stream.EndWrite, null);
task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
return task;
}
catch (Exception e)
{
error(e);
return null;
}
}
}
}