TcpDuplexSessionChannel.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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.NetTcp
  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. if (client.Connected)
  112. frame.WriteEndRecord ();
  113. session = null;
  114. }
  115. public override void Send (Message message)
  116. {
  117. Send (message, DefaultSendTimeout);
  118. }
  119. public override void Send (Message message, TimeSpan timeout)
  120. {
  121. ThrowIfDisposedOrNotOpen ();
  122. if (timeout <= TimeSpan.Zero)
  123. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  124. if (!is_service_side) {
  125. if (message.Headers.To == null)
  126. message.Headers.To = RemoteAddress.Uri;
  127. }
  128. client.SendTimeout = (int) timeout.TotalMilliseconds;
  129. Logger.LogMessage (MessageLogSourceKind.TransportSend, ref message, info.BindingElement.MaxReceivedMessageSize);
  130. frame.WriteSizedMessage (message);
  131. }
  132. public override bool TryReceive (TimeSpan timeout, out Message message)
  133. {
  134. ThrowIfDisposedOrNotOpen ();
  135. // FIXME: there seems to be some pipeline or channel-
  136. // recycling issues, which could be mostly workarounded
  137. // by delaying input receiver.
  138. // This place is not ideal, but it covers both loops in
  139. // ChannelDispatcher and DuplexClientRuntimeChannel.
  140. Thread.Sleep (50);
  141. if (timeout <= TimeSpan.Zero)
  142. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  143. client.ReceiveTimeout = (int) timeout.TotalMilliseconds;
  144. message = frame.ReadSizedMessage ();
  145. // FIXME: this may not be precise, but connection might be reused for some weird socket state transition (that's what happens). So as a workaround, avoid closing the session by sending EndRecord from this channel at OnClose().
  146. if (message == null) {
  147. session = null;
  148. return false;
  149. }
  150. Logger.LogMessage (MessageLogSourceKind.TransportReceive, ref message, info.BindingElement.MaxReceivedMessageSize);
  151. return true;
  152. }
  153. public override bool WaitForMessage (TimeSpan timeout)
  154. {
  155. ThrowIfDisposedOrNotOpen ();
  156. if (client.Available > 0)
  157. return true;
  158. DateTime start = DateTime.Now;
  159. do {
  160. Thread.Sleep (50);
  161. if (client.Available > 0)
  162. return true;
  163. } while (DateTime.Now - start < timeout);
  164. return false;
  165. }
  166. // CommunicationObject
  167. [MonoTODO]
  168. protected override void OnAbort ()
  169. {
  170. if (session != null)
  171. session.Close (TimeSpan.FromTicks (0));
  172. if (client != null)
  173. client.Close ();
  174. }
  175. protected override void OnClose (TimeSpan timeout)
  176. {
  177. if (session != null)
  178. session.Close (timeout);
  179. if (client != null)
  180. client.Close ();
  181. }
  182. protected override void OnOpen (TimeSpan timeout)
  183. {
  184. if (! is_service_side) {
  185. NetworkStream ns = client.GetStream ();
  186. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns, is_service_side) {
  187. Encoder = this.Encoder,
  188. Via = this.Via };
  189. frame.ProcessPreambleInitiator ();
  190. frame.ProcessPreambleAckInitiator ();
  191. session = new TcpDuplexSession (this); // make sure to shutdown the session once it has initiated one.
  192. } else {
  193. // server side
  194. Stream s = client.GetStream ();
  195. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  196. // FIXME: use retrieved record properties in the request processing.
  197. frame.ProcessPreambleRecipient ();
  198. frame.ProcessPreambleAckRecipient ();
  199. }
  200. }
  201. }
  202. }