/
TCPClient.cs
359 lines (299 loc) · 13.2 KB
/
TCPClient.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpClient class provide TCP services at a higher level
// of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
// is used to create a Client connection to a remote host.
public class TcpClient : IDisposable
{
private AddressFamily _family;
private Socket _clientSocket = null!; // initialized by helper called from ctor
private NetworkStream? _dataStream;
private volatile int _disposed;
private bool _active;
private bool Disposed => _disposed != 0;
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient() : this(AddressFamily.Unknown)
{
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, family);
if (family is not (AddressFamily.InterNetwork or AddressFamily.InterNetworkV6 or AddressFamily.Unknown))
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family));
}
_family = family;
InitializeClientSocket();
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point.
public TcpClient(IPEndPoint localEP)
{
ArgumentNullException.ThrowIfNull(localEP);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP);
_family = localEP.AddressFamily; // set before calling CreateSocket
InitializeClientSocket();
_clientSocket.Bind(localEP);
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on
// the specified host.
public TcpClient(string hostname, int port) : this(AddressFamily.Unknown)
{
ArgumentNullException.ThrowIfNull(hostname);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, hostname);
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
try
{
Connect(hostname, port);
}
catch
{
_clientSocket?.Close();
throw;
}
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
_clientSocket = acceptedSocket;
_active = true;
}
// Used by the class to indicate that a connection has been made.
protected bool Active
{
get { return _active; }
set { _active = value; }
}
public int Available => Client?.Available ?? 0;
// Used by the class to provide the underlying network socket.
public Socket Client
{
get { return Disposed ? null! : _clientSocket; }
set
{
_clientSocket = value;
_family = _clientSocket?.AddressFamily ?? AddressFamily.Unknown;
if (_clientSocket == null)
{
InitializeClientSocket();
}
}
}
public bool Connected => Client?.Connected ?? false;
public bool ExclusiveAddressUse
{
get { return Client?.ExclusiveAddressUse ?? false; }
set
{
if (_clientSocket != null)
{
_clientSocket.ExclusiveAddressUse = value;
}
}
}
// Connects the Client to the specified port on the specified host.
public void Connect(string hostname, int port)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(hostname);
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
Client.Connect(hostname, port);
_family = Client.AddressFamily;
_active = true;
}
// Connects the Client to the specified port on the specified host.
public void Connect(IPAddress address, int port)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(address);
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
}
// Connect the Client to the specified end point.
public void Connect(IPEndPoint remoteEP)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(remoteEP);
Client.Connect(remoteEP);
_family = Client.AddressFamily;
_active = true;
}
public void Connect(IPAddress[] ipAddresses, int port)
{
Client.Connect(ipAddresses, port);
_family = Client.AddressFamily;
_active = true;
}
public Task ConnectAsync(IPAddress address, int port) =>
CompleteConnectAsync(Client.ConnectAsync(address, port));
public Task ConnectAsync(string host, int port) =>
CompleteConnectAsync(Client.ConnectAsync(host, port));
public Task ConnectAsync(IPAddress[] addresses, int port) =>
CompleteConnectAsync(Client.ConnectAsync(addresses, port));
/// <summary>
/// Connects the client to a remote TCP host using the specified endpoint as an asynchronous operation.
/// </summary>
/// <param name="remoteEP">The <see cref="IPEndPoint"/> to which you intend to connect.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public Task ConnectAsync(IPEndPoint remoteEP) =>
CompleteConnectAsync(Client.ConnectAsync(remoteEP));
private async Task CompleteConnectAsync(Task task)
{
await task.ConfigureAwait(false);
_active = true;
}
public ValueTask ConnectAsync(IPAddress address, int port, CancellationToken cancellationToken) =>
CompleteConnectAsync(Client.ConnectAsync(address, port, cancellationToken));
public ValueTask ConnectAsync(string host, int port, CancellationToken cancellationToken) =>
CompleteConnectAsync(Client.ConnectAsync(host, port, cancellationToken));
public ValueTask ConnectAsync(IPAddress[] addresses, int port, CancellationToken cancellationToken) =>
CompleteConnectAsync(Client.ConnectAsync(addresses, port, cancellationToken));
/// <summary>
/// Connects the client to a remote TCP host using the specified endpoint as an asynchronous operation.
/// </summary>
/// <param name="remoteEP">The <see cref="IPEndPoint"/> to which you intend to connect.</param>
/// <param name="cancellationToken">A cancellation token used to propagate notification that this operation should be canceled.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public ValueTask ConnectAsync(IPEndPoint remoteEP, CancellationToken cancellationToken) =>
CompleteConnectAsync(Client.ConnectAsync(remoteEP, cancellationToken));
private async ValueTask CompleteConnectAsync(ValueTask task)
{
await task.ConfigureAwait(false);
_active = true;
}
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state) =>
Client.BeginConnect(address, port, requestCallback, state);
public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state) =>
Client.BeginConnect(host, port, requestCallback, state);
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state) =>
Client.BeginConnect(addresses, port, requestCallback, state);
public void EndConnect(IAsyncResult asyncResult)
{
_clientSocket.EndConnect(asyncResult);
_active = true;
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
ThrowIfDisposed();
if (!Connected)
{
throw new InvalidOperationException(SR.net_notconnected);
}
return _dataStream ??= new NetworkStream(Client, true);
}
public void Close() => Dispose();
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
{
if (disposing)
{
NetworkStream? dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
}
else
{
// If the NetworkStream wasn't created, the Socket might
// still be there and needs to be closed. In the case in which
// we are bound to a local IPEndPoint this will remove the
// binding and free up the IPEndPoint for later uses.
Socket chkClientSocket = Volatile.Read(ref _clientSocket);
if (chkClientSocket != null)
{
try
{
chkClientSocket.InternalShutdown(SocketShutdown.Both);
}
finally
{
chkClientSocket.Close();
}
}
}
GC.SuppressFinalize(this);
}
}
}
public void Dispose() => Dispose(true);
~TcpClient() => Dispose(false);
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); }
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); }
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); }
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); }
}
// Gets or sets the value of the connection's linger option.
[DisallowNull]
public LingerOption? LingerState
{
get { return Client.LingerState; }
set { Client.LingerState = value!; }
}
// Enables or disables delay when send or receive buffers are full.
public bool NoDelay
{
get { return Client.NoDelay; }
set { Client.NoDelay = value; }
}
private void InitializeClientSocket()
{
Debug.Assert(_clientSocket == null);
if (_family == AddressFamily.Unknown)
{
// If AF was not explicitly set try to initialize dual mode socket or fall-back to IPv4.
_clientSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
if (_clientSocket.AddressFamily == AddressFamily.InterNetwork)
{
_family = AddressFamily.InterNetwork;
}
}
else
{
_clientSocket = new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
}
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(Disposed, this);
}
}
}