NetworkStream.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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
  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.Connected)
  62. throw new ArgumentException ("Not connected", "socket");
  63. if (socket.SocketType != SocketType.Stream)
  64. throw new ArgumentException ("Socket is not of type Stream", "socket");
  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
  128. public override int ReadTimeout
  129. {
  130. get {
  131. return(socket.ReceiveTimeout);
  132. }
  133. set {
  134. if (value <= 0 && value != Timeout.Infinite) {
  135. throw new ArgumentOutOfRangeException ("value", "The value specified is less than or equal to zero and is not Infinite.");
  136. }
  137. socket.ReceiveTimeout = value;
  138. }
  139. }
  140. #endif
  141. protected Socket Socket {
  142. get {
  143. return socket;
  144. }
  145. }
  146. protected bool Writeable {
  147. get {
  148. return writeable;
  149. }
  150. set {
  151. writeable = value;
  152. }
  153. }
  154. #if NET_2_0
  155. public override int WriteTimeout
  156. {
  157. get {
  158. return(socket.SendTimeout);
  159. }
  160. set {
  161. if (value <= 0 && value != Timeout.Infinite) {
  162. throw new ArgumentOutOfRangeException ("value", "The value specified is less than or equal to zero and is not Infinite");
  163. }
  164. socket.SendTimeout = value;
  165. }
  166. }
  167. #endif
  168. public override IAsyncResult BeginRead (byte [] buffer, int offset, int size,
  169. AsyncCallback callback, object state)
  170. {
  171. CheckDisposed ();
  172. IAsyncResult retval;
  173. if (buffer == null)
  174. throw new ArgumentNullException ("buffer is null");
  175. int len = buffer.Length;
  176. if(offset<0 || offset>len) {
  177. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  178. }
  179. if(size<0 || offset+size>len) {
  180. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  181. }
  182. try {
  183. retval = socket.BeginReceive (buffer, offset, size, 0, callback, state);
  184. } catch (Exception e) {
  185. throw new IOException ("BeginReceive failure", e);
  186. }
  187. return retval;
  188. }
  189. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int size,
  190. AsyncCallback callback, object state)
  191. {
  192. CheckDisposed ();
  193. IAsyncResult retval;
  194. if (buffer == null)
  195. throw new ArgumentNullException ("buffer is null");
  196. int len = buffer.Length;
  197. if(offset<0 || offset>len) {
  198. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  199. }
  200. if(size<0 || offset+size>len) {
  201. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  202. }
  203. try {
  204. retval = socket.BeginSend (buffer, offset, size, 0, callback, state);
  205. } catch {
  206. throw new IOException ("BeginWrite failure");
  207. }
  208. return retval;
  209. }
  210. ~NetworkStream ()
  211. {
  212. Dispose (false);
  213. }
  214. public override void Close ()
  215. {
  216. ((IDisposable) this).Dispose ();
  217. }
  218. #if NET_2_0
  219. public void Close (int timeout)
  220. {
  221. if (timeout < -1) {
  222. throw new ArgumentOutOfRangeException ("timeout", "timeout is less than -1");
  223. }
  224. System.Timers.Timer close_timer = new System.Timers.Timer ();
  225. close_timer.Elapsed += new ElapsedEventHandler (OnTimeoutClose);
  226. /* NB timeout is in milliseconds here, cf
  227. * seconds in Socket.Close(int)
  228. */
  229. close_timer.Interval = timeout;
  230. close_timer.AutoReset = false;
  231. close_timer.Enabled = true;
  232. }
  233. private void OnTimeoutClose (object source, ElapsedEventArgs e)
  234. {
  235. this.Close ();
  236. }
  237. #endif
  238. protected
  239. #if NET_2_0
  240. override
  241. #else
  242. virtual
  243. #endif
  244. void Dispose (bool disposing)
  245. {
  246. if (disposed)
  247. return;
  248. disposed = true;
  249. if (owns_socket) {
  250. Socket s = socket;
  251. if (s != null)
  252. s.Close ();
  253. }
  254. socket = null;
  255. }
  256. public override int EndRead (IAsyncResult ar)
  257. {
  258. CheckDisposed ();
  259. int res;
  260. if (ar == null)
  261. throw new ArgumentNullException ("async result is null");
  262. try {
  263. res = socket.EndReceive (ar);
  264. } catch (Exception e) {
  265. throw new IOException ("EndRead failure", e);
  266. }
  267. return res;
  268. }
  269. public override void EndWrite (IAsyncResult ar)
  270. {
  271. CheckDisposed ();
  272. if (ar == null)
  273. throw new ArgumentNullException ("async result is null");
  274. try {
  275. socket.EndSend (ar);
  276. } catch (Exception e) {
  277. throw new IOException ("EndWrite failure", e);
  278. }
  279. }
  280. public override void Flush ()
  281. {
  282. // network streams are non-buffered, this is a no-op
  283. }
  284. void IDisposable.Dispose ()
  285. {
  286. Dispose (true);
  287. GC.SuppressFinalize (this);
  288. }
  289. public override int Read ([In,Out] byte [] buffer, int offset, int size)
  290. {
  291. CheckDisposed ();
  292. int res;
  293. if (buffer == null)
  294. throw new ArgumentNullException ("buffer is null");
  295. if(offset<0 || offset>buffer.Length) {
  296. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  297. }
  298. if(size < 0 || offset+size>buffer.Length) {
  299. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  300. }
  301. try {
  302. res = socket.Receive (buffer, offset, size, 0);
  303. } catch (Exception e) {
  304. throw new IOException ("Read failure", e);
  305. }
  306. return res;
  307. }
  308. public override long Seek (long offset, SeekOrigin origin)
  309. {
  310. // NetworkStream objects do not support seeking.
  311. throw new NotSupportedException ();
  312. }
  313. public override void SetLength (long value)
  314. {
  315. // NetworkStream objects do not support SetLength
  316. throw new NotSupportedException ();
  317. }
  318. public override void Write (byte [] buffer, int offset, int size)
  319. {
  320. CheckDisposed ();
  321. if (buffer == null)
  322. throw new ArgumentNullException ("buffer");
  323. if (offset < 0 || offset > buffer.Length)
  324. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  325. if (size < 0 || size > buffer.Length - offset)
  326. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  327. try {
  328. int count = 0;
  329. while (size - count > 0) {
  330. count += socket.Send (buffer, offset + count, size - count, 0);
  331. }
  332. } catch (Exception e) {
  333. throw new IOException ("Write failure", e);
  334. }
  335. }
  336. private void CheckDisposed ()
  337. {
  338. if (disposed)
  339. throw new ObjectDisposedException (GetType().FullName);
  340. }
  341. #if TARGET_JVM
  342. public void ChangeToSSLSocket()
  343. {
  344. socket.ChangeToSSL();
  345. }
  346. #endif
  347. }
  348. }