-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
NetworkStream.cs
1308 lines (1126 loc) · 43.6 KB
/
NetworkStream.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="NetworkStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.Sockets {
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Permissions;
using System.Threading.Tasks;
/// <devdoc>
/// <para>
/// Provides the underlying stream of data for network access.
/// </para>
/// </devdoc>
public class NetworkStream : Stream {
/// <devdoc>
/// <para>
/// Used by the class to hold the underlying socket the stream uses.
/// </para>
/// </devdoc>
private Socket m_StreamSocket;
/// <devdoc>
/// <para>
/// Used by the class to indicate that the stream is m_Readable.
/// </para>
/// </devdoc>
private bool m_Readable;
/// <devdoc>
/// <para>
/// Used by the class to indicate that the stream is writable.
/// </para>
/// </devdoc>
private bool m_Writeable;
private bool m_OwnsSocket;
/// <devdoc>
/// <para>Creates a new instance of the <see cref='System.Net.Sockets.NetworkStream'/> without initalization.</para>
/// </devdoc>
internal NetworkStream() {
m_OwnsSocket = true;
}
// Can be constructed directly out of a socket
/// <devdoc>
/// <para>Creates a new instance of the <see cref='System.Net.Sockets.NetworkStream'/> class for the specified <see cref='System.Net.Sockets.Socket'/>.</para>
/// </devdoc>
public NetworkStream(Socket socket) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
if (socket == null) {
throw new ArgumentNullException("socket");
}
InitNetworkStream(socket, FileAccess.ReadWrite);
#if DEBUG
}
#endif
}
//UEUE (see FileStream)
// ownsHandle: true if the file handle will be owned by this NetworkStream instance; otherwise, false.
public NetworkStream(Socket socket, bool ownsSocket) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
if (socket == null) {
throw new ArgumentNullException("socket");
}
InitNetworkStream(socket, FileAccess.ReadWrite);
m_OwnsSocket = ownsSocket;
#if DEBUG
}
#endif
}
internal NetworkStream(NetworkStream networkStream, bool ownsSocket) {
Socket socket = networkStream.Socket;
if (socket == null) {
throw new ArgumentNullException("networkStream");
}
InitNetworkStream(socket, FileAccess.ReadWrite);
m_OwnsSocket = ownsSocket;
}
// Create with a socket and access mode
/// <devdoc>
/// <para>Creates a new instance of the <see cref='System.Net.Sockets.NetworkStream'/> class for the specified <see cref='System.Net.Sockets.Socket'/> with the specified access rights.</para>
/// </devdoc>
public NetworkStream(Socket socket, FileAccess access) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
if (socket == null) {
throw new ArgumentNullException("socket");
}
InitNetworkStream(socket, access);
#if DEBUG
}
#endif
}
public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
if (socket == null) {
throw new ArgumentNullException("socket");
}
InitNetworkStream(socket, access);
m_OwnsSocket = ownsSocket;
#if DEBUG
}
#endif
}
//
// Socket - provides access to socket for stream closing
//
protected Socket Socket {
get {
return m_StreamSocket;
}
}
internal Socket InternalSocket {
get {
Socket chkSocket = m_StreamSocket;
if (m_CleanedUp || chkSocket == null) {
throw new ObjectDisposedException(this.GetType().FullName);
}
return chkSocket;
}
}
internal void InternalAbortSocket()
{
if (!m_OwnsSocket)
{
throw new InvalidOperationException();
}
Socket chkSocket = m_StreamSocket;
if (m_CleanedUp || chkSocket == null)
{
return;
}
try
{
chkSocket.Close(0);
}
catch (ObjectDisposedException)
{
}
}
internal void ConvertToNotSocketOwner() {
m_OwnsSocket = false;
// Suppress for finialization still allow proceed the requests
GC.SuppressFinalize(this);
}
/// <devdoc>
/// <para>
/// Used by the class to indicate that the stream is m_Readable.
/// </para>
/// </devdoc>
protected bool Readable {
get {
return m_Readable;
}
set {
m_Readable = value;
}
}
/// <devdoc>
/// <para>
/// Used by the class to indicate that the stream is writable.
/// </para>
/// </devdoc>
protected bool Writeable {
get {
return m_Writeable;
}
set {
m_Writeable = value;
}
}
/// <devdoc>
/// <para>
/// Indicates that data can be read from the stream.
/// We return the readability of this stream. This is a read only property.
/// </para>
/// </devdoc>
public override bool CanRead {
get {
return m_Readable;
}
}
/// <devdoc>
/// <para>
/// Indicates that the stream can seek a specific location
/// in the stream. This property always returns <see langword='false'/>
/// .
/// </para>
/// </devdoc>
public override bool CanSeek {
get {
return false;
}
}
/// <devdoc>
/// <para>
/// Indicates that data can be written to the stream.
/// </para>
/// </devdoc>
public override bool CanWrite {
get {
return m_Writeable;
}
}
/// <devdoc>
/// <para>Indicates whether we can timeout</para>
/// </devdoc>
public override bool CanTimeout {
get {
return true; // should we check for Connected state?
}
}
/// <devdoc>
/// <para>Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets,
/// so we map this to -1, and if you set 0, we cannot support it</para>
/// </devdoc>
public override int ReadTimeout {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
int timeout = (int)m_StreamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
if (timeout == 0) {
return -1;
}
return timeout;
#if DEBUG
}
#endif
}
set {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
if (value<=0 && value!=System.Threading.Timeout.Infinite) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
}
SetSocketTimeoutOption(SocketShutdown.Receive, value, false);
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets,
/// so we map this to -1, and if you set 0, we cannot support it</para>
/// </devdoc>
public override int WriteTimeout {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
int timeout = (int)m_StreamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
if (timeout == 0) {
return -1;
}
return timeout;
#if DEBUG
}
#endif
}
set {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
if (value <= 0 && value != System.Threading.Timeout.Infinite) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
}
SetSocketTimeoutOption(SocketShutdown.Send, value, false);
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// Indicates data is available on the stream to be read.
/// This property checks to see if at least one byte of data is currently available
/// </para>
/// </devdoc>
public virtual bool DataAvailable {
get {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
Socket chkStreamSocket = m_StreamSocket;
if(chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
// Ask the socket how many bytes are available. If it's
// not zero, return true.
return chkStreamSocket.Available != 0;
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// The length of data available on the stream. Always throws <see cref='NotSupportedException'/>.
/// </para>
/// </devdoc>
public override long Length {
get {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
/// <devdoc>
/// <para>
/// Gets or sets the position in the stream. Always throws <see cref='NotSupportedException'/>.
/// </para>
/// </devdoc>
public override long Position {
get {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
set {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
/// <devdoc>
/// <para>
/// Seeks a specific position in the stream. This method is not supported by the
/// <see cref='NetworkStream'/> class.
/// </para>
/// </devdoc>
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
/*++
InitNetworkStream - initialize a network stream.
This is the common NetworkStream constructor, called whenever a
network stream is created. We validate the socket, set a few
options, and call our parent's initializer.
Input:
S - Socket to be used.
Access - Access type desired.
Returns:
Nothing, but may throw an exception.
--*/
internal void InitNetworkStream(Socket socket, FileAccess Access) {
//
// parameter validation
//
if (!socket.Blocking) {
throw new IOException(SR.GetString(SR.net_sockets_blocking));
}
if (!socket.Connected) {
throw new IOException(SR.GetString(SR.net_notconnected));
}
if (socket.SocketType != SocketType.Stream) {
throw new IOException(SR.GetString(SR.net_notstream));
}
m_StreamSocket = socket;
switch (Access) {
case FileAccess.Read:
m_Readable = true;
break;
case FileAccess.Write:
m_Writeable = true;
break;
case FileAccess.ReadWrite:
default: // assume FileAccess.ReadWrite
m_Readable = true;
m_Writeable = true;
break;
}
}
internal bool PollRead() {
if (m_CleanedUp) {
return false;
}
Socket chkStreamSocket = m_StreamSocket;
if (chkStreamSocket == null) {
return false;
}
return chkStreamSocket.Poll(0, SelectMode.SelectRead);
}
internal bool Poll(int microSeconds, SelectMode mode) {
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
Socket chkStreamSocket = m_StreamSocket;
if (chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
return chkStreamSocket.Poll(microSeconds, mode);
}
/*++
Read - provide core Read functionality.
Provide core read functionality. All we do is call through to the
socket Receive functionality.
Input:
Buffer - Buffer to read into.
Offset - Offset into the buffer where we're to read.
Count - Number of bytes to read.
Returns:
Number of bytes we read, or 0 if the socket is closed.
--*/
/// <devdoc>
/// <para>
/// Reads data from the stream.
/// </para>
/// </devdoc>
//UEUE
public override int Read([In, Out] byte[] buffer, int offset, int size) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
bool canRead = CanRead; // Prevent ---- with Dispose.
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!canRead) {
throw new InvalidOperationException(SR.GetString(SR.net_writeonlystream));
}
//
// parameter validation
//
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
Socket chkStreamSocket = m_StreamSocket;
if (chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
try {
int bytesTransferred = chkStreamSocket.Receive(buffer, offset, size, 0);
return bytesTransferred;
}
catch (Exception exception) {
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}
//
// some sort of error occured on the socket call,
// set the SocketException as InnerException and throw
//
throw new IOException(SR.GetString(SR.net_io_readfailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
/*++
Write - provide core Write functionality.
Provide core write functionality. All we do is call through to the
socket Send method..
Input:
Buffer - Buffer to write from.
Offset - Offset into the buffer from where we'll start writing.
Count - Number of bytes to write.
Returns:
Number of bytes written. We'll throw an exception if we
can't write everything. It's brutal, but there's no other
way to indicate an error.
--*/
/// <devdoc>
/// <para>
/// Writes data to the stream..
/// </para>
/// </devdoc>
public override void Write(byte[] buffer, int offset, int size) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
bool canWrite = CanWrite; // Prevent ---- with Dispose.
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!canWrite) {
throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
}
//
// parameter validation
//
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
Socket chkStreamSocket = m_StreamSocket;
if(chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
}
try {
//
// since the socket is in blocking mode this will always complete
// after ALL the requested number of bytes was transferred
//
chkStreamSocket.Send(buffer, offset, size, SocketFlags.None);
}
catch (Exception exception) {
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}
//
// some sort of error occured on the socket call,
// set the SocketException as InnerException and throw
//
throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
private int m_CloseTimeout = Socket.DefaultCloseTimeout; // 1 ms; -1 = respect linger options
public void Close(int timeout) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
if (timeout < -1) {
throw new ArgumentOutOfRangeException("timeout");
}
m_CloseTimeout = timeout;
Close();
#if DEBUG
}
#endif
}
private volatile bool m_CleanedUp = false;
protected override void Dispose(bool disposing) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
// Mark this as disposed before changing anything else.
bool cleanedUp = m_CleanedUp;
m_CleanedUp = true;
if (!cleanedUp && disposing) {
//
// only resource we need to free is the network stream, since this
// is based on the client socket, closing the stream will cause us
// to flush the data to the network, close the stream and (in the
// NetoworkStream code) close the socket as well.
//
if (m_StreamSocket!=null) {
m_Readable = false;
m_Writeable = false;
if (m_OwnsSocket) {
//
// if we own the Socket (false by default), close it
// ignoring possible exceptions (eg: the user told us
// that we own the Socket but it closed at some point of time,
// here we would get an ObjectDisposedException)
//
Socket chkStreamSocket = m_StreamSocket;
if (chkStreamSocket!=null) {
chkStreamSocket.InternalShutdown(SocketShutdown.Both);
chkStreamSocket.Close(m_CloseTimeout);
}
}
}
}
#if DEBUG
}
#endif
base.Dispose(disposing);
}
~NetworkStream() {
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.Finalization);
// using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) {
#endif
Dispose(false);
#if DEBUG
// }
#endif
}
/// <devdoc>
/// <para>
/// Indicates whether the stream is still connected
/// </para>
/// </devdoc>
internal bool Connected {
get {
Socket socket = m_StreamSocket;
if (!m_CleanedUp && socket !=null && socket.Connected) {
return true;
} else {
return false;
}
}
}
/*++
BeginRead - provide async read functionality.
This method provides async read functionality. All we do is
call through to the underlying socket async read.
Input:
buffer - Buffer to read into.
offset - Offset into the buffer where we're to read.
size - Number of bytes to read.
Returns:
An IASyncResult, representing the read.
--*/
/// <devdoc>
/// <para>
/// Begins an asychronous read from a stream.
/// </para>
/// </devdoc>
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool canRead = CanRead; // Prevent ---- with Dispose.
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!canRead) {
throw new InvalidOperationException(SR.GetString(SR.net_writeonlystream));
}
//
// parameter validation
//
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
Socket chkStreamSocket = m_StreamSocket;
if(chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
try {
IAsyncResult asyncResult =
chkStreamSocket.BeginReceive(
buffer,
offset,
size,
SocketFlags.None,
callback,
state);
return asyncResult;
}
catch (Exception exception) {
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}
//
// some sort of error occured on the socket call,
// set the SocketException as InnerException and throw
//
throw new IOException(SR.GetString(SR.net_io_readfailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
internal virtual IAsyncResult UnsafeBeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
{
bool canRead = CanRead; // Prevent ---- with Dispose.
if (m_CleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!canRead)
{
throw new InvalidOperationException(SR.GetString(SR.net_writeonlystream));
}
Socket chkStreamSocket = m_StreamSocket;
if (chkStreamSocket == null)
{
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
try
{
IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginReceive(
buffer,
offset,
size,
SocketFlags.None,
callback,
state);
return asyncResult;
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
//
// some sort of error occured on the socket call,
// set the SocketException as InnerException and throw
//
throw new IOException(SR.GetString(SR.net_io_readfailure, exception.Message), exception);
}
}
/*++
EndRead - handle the end of an async read.
This method is called when an async read is completed. All we
do is call through to the core socket EndReceive functionality.
Input:
buffer - Buffer to read into.
offset - Offset into the buffer where we're to read.
size - Number of bytes to read.
Returns:
The number of bytes read. May throw an exception.
--*/
/// <devdoc>
/// <para>
/// Handle the end of an asynchronous read.
/// </para>
/// </devdoc>
public override int EndRead(IAsyncResult asyncResult) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
//
// parameter validation
//
if (asyncResult==null) {
throw new ArgumentNullException("asyncResult");
}
Socket chkStreamSocket = m_StreamSocket;
if(chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
}
try {
int bytesTransferred = chkStreamSocket.EndReceive(asyncResult);
return bytesTransferred;
}
catch (Exception exception) {
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}
//
// some sort of error occured on the socket call,
// set the SocketException as InnerException and throw
//
throw new IOException(SR.GetString(SR.net_io_readfailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
/*++
BeginWrite - provide async write functionality.
This method provides async write functionality. All we do is
call through to the underlying socket async send.
Input:
buffer - Buffer to write into.
offset - Offset into the buffer where we're to write.
size - Number of bytes to written.
Returns:
An IASyncResult, representing the write.
--*/
/// <devdoc>
/// <para>
/// Begins an asynchronous write to a stream.
/// </para>
/// </devdoc>
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool canWrite = CanWrite; // Prevent ---- with Dispose.
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!canWrite) {
throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
}
//
// parameter validation
//
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
Socket chkStreamSocket = m_StreamSocket;
if(chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
}
try {
//
// call BeginSend on the Socket.
//
IAsyncResult asyncResult =
chkStreamSocket.BeginSend(
buffer,
offset,
size,
SocketFlags.None,
callback,
state);
return asyncResult;
}
catch (Exception exception) {
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}
//
// some sort of error occured on the socket call,
// set the SocketException as InnerException and throw
//
throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
}
#if DEBUG
}
#endif
}
internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool canWrite = CanWrite; // Prevent ---- with Dispose.
if (m_CleanedUp){
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!canWrite) {
throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
}
Socket chkStreamSocket = m_StreamSocket;
if(chkStreamSocket == null) {
throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
}
try {
//
// call BeginSend on the Socket.
//
IAsyncResult asyncResult =
chkStreamSocket.UnsafeBeginSend(
buffer,
offset,
size,
SocketFlags.None,
callback,
state);
return asyncResult;
}
catch (Exception exception) {
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}