2
0

NetworkStream.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //
  2. // System.Net.Sockets.NetworkStream.cs
  3. //
  4. // Author:
  5. // Miguel de Icaza ([email protected])
  6. // Sridhar Kulkarni <[email protected]>
  7. //
  8. // (C) 2002 Ximian, Inc. http://www.ximian.com
  9. // Copyright (C) 2002-2006 Novell, Inc. http://www.novell.com
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.IO;
  32. using System.Runtime.InteropServices;
  33. #if NET_2_0 && !NET_2_1
  34. using System.Timers;
  35. using System.Threading;
  36. #endif
  37. namespace System.Net.Sockets
  38. {
  39. public class NetworkStream : Stream, IDisposable {
  40. FileAccess access;
  41. Socket socket;
  42. bool owns_socket;
  43. bool readable, writeable;
  44. bool disposed = false;
  45. public NetworkStream (Socket socket)
  46. : this (socket, FileAccess.ReadWrite, false)
  47. {
  48. }
  49. public NetworkStream (Socket socket, bool owns_socket)
  50. : this (socket, FileAccess.ReadWrite, owns_socket)
  51. {
  52. }
  53. public NetworkStream (Socket socket, FileAccess access)
  54. : this (socket, access, false)
  55. {
  56. }
  57. public NetworkStream (Socket socket, FileAccess access, bool owns_socket)
  58. {
  59. if (socket == null)
  60. throw new ArgumentNullException ("socket is null");
  61. if (socket.SocketType != SocketType.Stream)
  62. throw new ArgumentException ("Socket is not of type Stream", "socket");
  63. if (!socket.Connected)
  64. throw new IOException ("Not connected");
  65. if (!socket.Blocking)
  66. throw new IOException ("Operation not allowed on a non-blocking socket.");
  67. this.socket = socket;
  68. this.owns_socket = owns_socket;
  69. this.access = access;
  70. readable = CanRead;
  71. writeable = CanWrite;
  72. }
  73. public override bool CanRead {
  74. get {
  75. return access == FileAccess.ReadWrite || access == FileAccess.Read;
  76. }
  77. }
  78. public override bool CanSeek {
  79. get {
  80. // network sockets cant seek.
  81. return false;
  82. }
  83. }
  84. #if NET_2_0
  85. public override bool CanTimeout
  86. {
  87. get {
  88. return(true);
  89. }
  90. }
  91. #endif
  92. public override bool CanWrite {
  93. get {
  94. return access == FileAccess.ReadWrite || access == FileAccess.Write;
  95. }
  96. }
  97. public virtual bool DataAvailable {
  98. get {
  99. CheckDisposed ();
  100. return socket.Available > 0;
  101. }
  102. }
  103. public override long Length {
  104. get {
  105. // Network sockets always throw an exception
  106. throw new NotSupportedException ();
  107. }
  108. }
  109. public override long Position {
  110. get {
  111. // Network sockets always throw an exception
  112. throw new NotSupportedException ();
  113. }
  114. set {
  115. // Network sockets always throw an exception
  116. throw new NotSupportedException ();
  117. }
  118. }
  119. protected bool Readable {
  120. get {
  121. return readable;
  122. }
  123. set {
  124. readable = value;
  125. }
  126. }
  127. #if NET_2_0 && !NET_2_1
  128. #if TARGET_JVM
  129. [MonoNotSupported ("Not supported since Socket.ReceiveTimeout is not supported")]
  130. #endif
  131. public override int ReadTimeout
  132. {
  133. get {
  134. return(socket.ReceiveTimeout);
  135. }
  136. set {
  137. if (value <= 0 && value != Timeout.Infinite) {
  138. throw new ArgumentOutOfRangeException ("value", "The value specified is less than or equal to zero and is not Infinite.");
  139. }
  140. socket.ReceiveTimeout = value;
  141. }
  142. }
  143. #endif
  144. protected Socket Socket {
  145. get {
  146. return socket;
  147. }
  148. }
  149. protected bool Writeable {
  150. get {
  151. return writeable;
  152. }
  153. set {
  154. writeable = value;
  155. }
  156. }
  157. #if NET_2_0 && !NET_2_1
  158. #if TARGET_JVM
  159. [MonoNotSupported ("Not supported since Socket.SendTimeout is not supported")]
  160. #endif
  161. public override int WriteTimeout
  162. {
  163. get {
  164. return(socket.SendTimeout);
  165. }
  166. set {
  167. if (value <= 0 && value != Timeout.Infinite) {
  168. throw new ArgumentOutOfRangeException ("value", "The value specified is less than or equal to zero and is not Infinite");
  169. }
  170. socket.SendTimeout = value;
  171. }
  172. }
  173. #endif
  174. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  175. AsyncCallback callback, object state)
  176. {
  177. CheckDisposed ();
  178. IAsyncResult retval;
  179. if (buffer == null)
  180. throw new ArgumentNullException ("buffer is null");
  181. int len = buffer.Length;
  182. if(offset<0 || offset>len) {
  183. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  184. }
  185. if(size<0 || offset+size>len) {
  186. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  187. }
  188. try {
  189. retval = socket.BeginReceive (buffer, offset, size, 0, callback, state);
  190. } catch (Exception e) {
  191. throw new IOException ("BeginReceive failure", e);
  192. }
  193. return retval;
  194. }
  195. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  196. AsyncCallback callback, object state)
  197. {
  198. CheckDisposed ();
  199. IAsyncResult retval;
  200. if (buffer == null)
  201. throw new ArgumentNullException ("buffer is null");
  202. int len = buffer.Length;
  203. if(offset<0 || offset>len) {
  204. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  205. }
  206. if(size<0 || offset+size>len) {
  207. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  208. }
  209. try {
  210. retval = socket.BeginSend (buffer, offset, size, 0, callback, state);
  211. } catch {
  212. throw new IOException ("BeginWrite failure");
  213. }
  214. return retval;
  215. }
  216. ~NetworkStream ()
  217. {
  218. Dispose (false);
  219. }
  220. #if !NET_2_0
  221. public override void Close ()
  222. {
  223. ((IDisposable) this).Dispose ();
  224. }
  225. #endif
  226. #if NET_2_0 && !NET_2_1
  227. public void Close (int timeout)
  228. {
  229. if (timeout < -1) {
  230. throw new ArgumentOutOfRangeException ("timeout", "timeout is less than -1");
  231. }
  232. System.Timers.Timer close_timer = new System.Timers.Timer ();
  233. close_timer.Elapsed += new ElapsedEventHandler (OnTimeoutClose);
  234. /* NB timeout is in milliseconds here, cf
  235. * seconds in Socket.Close(int)
  236. */
  237. close_timer.Interval = timeout;
  238. close_timer.AutoReset = false;
  239. close_timer.Enabled = true;
  240. }
  241. private void OnTimeoutClose (object source, ElapsedEventArgs e)
  242. {
  243. this.Close ();
  244. }
  245. #endif
  246. protected
  247. #if NET_2_0
  248. override
  249. #else
  250. virtual
  251. #endif
  252. void Dispose (bool disposing)
  253. {
  254. if (disposed)
  255. return;
  256. disposed = true;
  257. if (owns_socket) {
  258. Socket s = socket;
  259. if (s != null)
  260. s.Close ();
  261. }
  262. socket = null;
  263. }
  264. public override int EndRead (IAsyncResult ar)
  265. {
  266. CheckDisposed ();
  267. int res;
  268. if (ar == null)
  269. throw new ArgumentNullException ("async result is null");
  270. try {
  271. res = socket.EndReceive (ar);
  272. } catch (Exception e) {
  273. throw new IOException ("EndRead failure", e);
  274. }
  275. return res;
  276. }
  277. public override void EndWrite (IAsyncResult ar)
  278. {
  279. CheckDisposed ();
  280. if (ar == null)
  281. throw new ArgumentNullException ("async result is null");
  282. try {
  283. socket.EndSend (ar);
  284. } catch (Exception e) {
  285. throw new IOException ("EndWrite failure", e);
  286. }
  287. }
  288. public override void Flush ()
  289. {
  290. // network streams are non-buffered, this is a no-op
  291. }
  292. void IDisposable.Dispose ()
  293. {
  294. Dispose (true);
  295. GC.SuppressFinalize (this);
  296. }
  297. public override int Read ([In,Out] byte [] buffer, int offset, int size)
  298. {
  299. CheckDisposed ();
  300. int res;
  301. if (buffer == null)
  302. throw new ArgumentNullException ("buffer is null");
  303. if(offset<0 || offset>buffer.Length) {
  304. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  305. }
  306. if(size < 0 || offset+size>buffer.Length) {
  307. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  308. }
  309. try {
  310. res = socket.Receive (buffer, offset, size, 0);
  311. } catch (Exception e) {
  312. throw new IOException ("Read failure", e);
  313. }
  314. return res;
  315. }
  316. public override long Seek (long offset, SeekOrigin origin)
  317. {
  318. // NetworkStream objects do not support seeking.
  319. throw new NotSupportedException ();
  320. }
  321. public override void SetLength (long value)
  322. {
  323. // NetworkStream objects do not support SetLength
  324. throw new NotSupportedException ();
  325. }
  326. public override void Write (byte [] buffer, int offset, int size)
  327. {
  328. CheckDisposed ();
  329. if (buffer == null)
  330. throw new ArgumentNullException ("buffer");
  331. if (offset < 0 || offset > buffer.Length)
  332. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  333. if (size < 0 || size > buffer.Length - offset)
  334. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  335. try {
  336. int count = 0;
  337. while (size - count > 0) {
  338. count += socket.Send (buffer, offset + count, size - count, 0);
  339. }
  340. } catch (Exception e) {
  341. throw new IOException ("Write failure", e);
  342. }
  343. }
  344. private void CheckDisposed ()
  345. {
  346. if (disposed)
  347. throw new ObjectDisposedException (GetType().FullName);
  348. }
  349. #if TARGET_JVM
  350. public void ChangeToSSLSocket()
  351. {
  352. socket.ChangeToSSL();
  353. }
  354. #endif
  355. }
  356. }