TcpDuplexSessionChannel.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //
  2. // TcpDuplexSessionChannel.cs
  3. //
  4. // Author:
  5. // Marcos Cobena ([email protected])
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // Copyright 2007 Marcos Cobena (http://www.youcannoteatbits.org/)
  9. //
  10. // Copyright (C) 2009 Novell, Inc (http://www.novell.com)
  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;
  32. using System.Collections.Generic;
  33. using System.IO;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using System.Runtime.Serialization;
  37. using System.Runtime.Serialization.Formatters.Binary;
  38. using System.ServiceModel.Channels;
  39. using System.Text;
  40. using System.Threading;
  41. using System.Xml;
  42. namespace System.ServiceModel.Channels
  43. {
  44. internal class TcpDuplexSessionChannel : DuplexChannelBase, IDuplexSessionChannel
  45. {
  46. class TcpDuplexSession : DuplexSessionBase
  47. {
  48. TcpDuplexSessionChannel owner;
  49. internal TcpDuplexSession (TcpDuplexSessionChannel owner)
  50. {
  51. this.owner = owner;
  52. }
  53. public override TimeSpan DefaultCloseTimeout {
  54. get { return owner.DefaultCloseTimeout; }
  55. }
  56. public override void Close (TimeSpan timeout)
  57. {
  58. owner.DiscardSession ();
  59. }
  60. }
  61. TcpChannelInfo info;
  62. TcpClient client;
  63. bool is_service_side;
  64. TcpBinaryFrameManager frame;
  65. TcpDuplexSession session; // do not use this directly. Use Session instead.
  66. EndpointAddress counterpart_address;
  67. public TcpDuplexSessionChannel (ChannelFactoryBase factory, TcpChannelInfo info, EndpointAddress address, Uri via)
  68. : base (factory, address, via)
  69. {
  70. is_service_side = false;
  71. this.info = info;
  72. // make sure to acquire TcpClient here.
  73. int explicitPort = Via.Port;
  74. client = new TcpClient (Via.Host, explicitPort <= 0 ? TcpTransportBindingElement.DefaultPort : explicitPort);
  75. counterpart_address = GetEndpointAddressFromTcpClient (client);
  76. }
  77. public TcpDuplexSessionChannel (ChannelListenerBase listener, TcpChannelInfo info, TcpClient client)
  78. : base (listener)
  79. {
  80. is_service_side = true;
  81. this.client = client;
  82. this.info = info;
  83. counterpart_address = GetEndpointAddressFromTcpClient (client);
  84. }
  85. EndpointAddress GetEndpointAddressFromTcpClient (TcpClient client)
  86. {
  87. IPEndPoint ep = (IPEndPoint) client.Client.RemoteEndPoint;
  88. return new EndpointAddress (new Uri ("net.tcp://" + ep));
  89. }
  90. public MessageEncoder Encoder {
  91. get { return info.MessageEncoder; }
  92. }
  93. public override EndpointAddress RemoteAddress {
  94. get { return base.RemoteAddress ?? counterpart_address; }
  95. }
  96. public override EndpointAddress LocalAddress {
  97. get { return base.LocalAddress ?? counterpart_address; }
  98. }
  99. public IDuplexSession Session {
  100. get {
  101. if (session == null)
  102. session = new TcpDuplexSession (this);
  103. return session;
  104. }
  105. }
  106. internal TcpClient TcpClient {
  107. get { return client; }
  108. }
  109. void DiscardSession ()
  110. {
  111. frame.ProcessEndRecordInitiator ();
  112. session = null;
  113. }
  114. public override void Send (Message message)
  115. {
  116. Send (message, DefaultSendTimeout);
  117. }
  118. public override void Send (Message message, TimeSpan timeout)
  119. {
  120. ThrowIfDisposedOrNotOpen ();
  121. if (timeout <= TimeSpan.Zero)
  122. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  123. if (!is_service_side) {
  124. if (message.Headers.To == null)
  125. message.Headers.To = RemoteAddress.Uri;
  126. if (message.Headers.ReplyTo == null)
  127. message.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
  128. } else {
  129. if (message.Headers.RelatesTo == null && OperationContext.Current.IncomingMessageHeaders != null)
  130. message.Headers.RelatesTo = OperationContext.Current.IncomingMessageHeaders.MessageId;
  131. }
  132. client.SendTimeout = (int) timeout.TotalMilliseconds;
  133. frame.WriteSizedMessage (message);
  134. // FIXME: should EndRecord be sent here?
  135. //if (is_service_side && client.Available > 0)
  136. // frame.ProcessEndRecordRecipient ();
  137. }
  138. public override Message Receive ()
  139. {
  140. return Receive (DefaultReceiveTimeout);
  141. }
  142. public override Message Receive (TimeSpan timeout)
  143. {
  144. ThrowIfDisposedOrNotOpen ();
  145. if (timeout <= TimeSpan.Zero)
  146. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  147. client.ReceiveTimeout = (int) timeout.TotalMilliseconds;
  148. return frame.ReadSizedMessage ();
  149. }
  150. public override bool TryReceive (TimeSpan timeout, out Message message)
  151. {
  152. try {
  153. DateTime start = DateTime.Now;
  154. message = Receive (timeout);
  155. if (message != null)
  156. return true;
  157. // received EndRecord, so close the session and return false instead.
  158. // (Closing channel here might not be a good idea, but right now I have no better way.)
  159. Close (timeout - (DateTime.Now - start));
  160. return false;
  161. } catch (TimeoutException) {
  162. message = null;
  163. return false;
  164. }
  165. }
  166. public override bool WaitForMessage (TimeSpan timeout)
  167. {
  168. ThrowIfDisposedOrNotOpen ();
  169. if (client.Available > 0)
  170. return true;
  171. DateTime start = DateTime.Now;
  172. do {
  173. Thread.Sleep (50);
  174. if (client.Available > 0)
  175. return true;
  176. } while (DateTime.Now - start < timeout);
  177. return false;
  178. }
  179. // CommunicationObject
  180. [MonoTODO]
  181. protected override void OnAbort ()
  182. {
  183. if (!is_service_side)
  184. if (session != null)
  185. session.Close (TimeSpan.FromTicks (0));
  186. if (client != null)
  187. client.Close ();
  188. }
  189. protected override void OnClose (TimeSpan timeout)
  190. {
  191. if (!is_service_side)
  192. if (session != null)
  193. session.Close (timeout);
  194. if (client != null)
  195. client.Close ();
  196. }
  197. protected override void OnOpen (TimeSpan timeout)
  198. {
  199. if (! is_service_side) {
  200. NetworkStream ns = client.GetStream ();
  201. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns, is_service_side) {
  202. Encoder = this.Encoder,
  203. Via = this.Via };
  204. frame.ProcessPreambleInitiator ();
  205. frame.ProcessPreambleAckInitiator ();
  206. } else {
  207. // server side
  208. Stream s = client.GetStream ();
  209. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  210. // FIXME: use retrieved record properties in the request processing.
  211. frame.ProcessPreambleRecipient ();
  212. frame.ProcessPreambleAckRecipient ();
  213. }
  214. }
  215. }
  216. }