TcpDuplexSessionChannel.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. } else {
  127. if (message.Headers.RelatesTo == null && OperationContext.Current.IncomingMessageHeaders != null)
  128. message.Headers.RelatesTo = OperationContext.Current.IncomingMessageHeaders.MessageId;
  129. }
  130. client.SendTimeout = (int) timeout.TotalMilliseconds;
  131. frame.WriteSizedMessage (message);
  132. // FIXME: should EndRecord be sent here?
  133. //if (is_service_side && client.Available > 0)
  134. // frame.ProcessEndRecordRecipient ();
  135. }
  136. public override Message Receive ()
  137. {
  138. return Receive (DefaultReceiveTimeout);
  139. }
  140. public override Message Receive (TimeSpan timeout)
  141. {
  142. ThrowIfDisposedOrNotOpen ();
  143. if (timeout <= TimeSpan.Zero)
  144. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  145. client.ReceiveTimeout = (int) timeout.TotalMilliseconds;
  146. return frame.ReadSizedMessage ();
  147. }
  148. public override bool TryReceive (TimeSpan timeout, out Message message)
  149. {
  150. try {
  151. DateTime start = DateTime.Now;
  152. message = Receive (timeout);
  153. if (message != null)
  154. return true;
  155. // received EndRecord, so close the session and return false instead.
  156. // (Closing channel here might not be a good idea, but right now I have no better way.)
  157. Close (timeout - (DateTime.Now - start));
  158. return false;
  159. } catch (TimeoutException) {
  160. message = null;
  161. return false;
  162. }
  163. }
  164. public override bool WaitForMessage (TimeSpan timeout)
  165. {
  166. ThrowIfDisposedOrNotOpen ();
  167. if (client.Available > 0)
  168. return true;
  169. DateTime start = DateTime.Now;
  170. do {
  171. Thread.Sleep (50);
  172. if (client.Available > 0)
  173. return true;
  174. } while (DateTime.Now - start < timeout);
  175. return false;
  176. }
  177. // CommunicationObject
  178. [MonoTODO]
  179. protected override void OnAbort ()
  180. {
  181. if (!is_service_side)
  182. if (session != null)
  183. session.Close (TimeSpan.FromTicks (0));
  184. if (client != null)
  185. client.Close ();
  186. }
  187. protected override void OnClose (TimeSpan timeout)
  188. {
  189. if (!is_service_side)
  190. if (session != null)
  191. session.Close (timeout);
  192. if (client != null)
  193. client.Close ();
  194. }
  195. protected override void OnOpen (TimeSpan timeout)
  196. {
  197. if (! is_service_side) {
  198. NetworkStream ns = client.GetStream ();
  199. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns, is_service_side) {
  200. Encoder = this.Encoder,
  201. Via = this.Via };
  202. frame.ProcessPreambleInitiator ();
  203. frame.ProcessPreambleAckInitiator ();
  204. } else {
  205. // server side
  206. Stream s = client.GetStream ();
  207. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  208. // FIXME: use retrieved record properties in the request processing.
  209. frame.ProcessPreambleRecipient ();
  210. frame.ProcessPreambleAckRecipient ();
  211. }
  212. }
  213. }
  214. }