TcpDuplexSessionChannel.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. 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. } else {
  128. if (message.Headers.RelatesTo == null && OperationContext.Current.IncomingMessageHeaders != null)
  129. message.Headers.RelatesTo = OperationContext.Current.IncomingMessageHeaders.MessageId;
  130. }
  131. client.SendTimeout = (int) timeout.TotalMilliseconds;
  132. frame.WriteSizedMessage (message);
  133. }
  134. public override bool TryReceive (TimeSpan timeout, out Message message)
  135. {
  136. ThrowIfDisposedOrNotOpen ();
  137. if (timeout <= TimeSpan.Zero)
  138. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  139. client.ReceiveTimeout = (int) timeout.TotalMilliseconds;
  140. message = frame.ReadSizedMessage ();
  141. // 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().
  142. if (message == null) {
  143. session = null;
  144. return false;
  145. }
  146. return true;
  147. }
  148. public override bool WaitForMessage (TimeSpan timeout)
  149. {
  150. ThrowIfDisposedOrNotOpen ();
  151. if (client.Available > 0)
  152. return true;
  153. DateTime start = DateTime.Now;
  154. do {
  155. Thread.Sleep (50);
  156. if (client.Available > 0)
  157. return true;
  158. } while (DateTime.Now - start < timeout);
  159. return false;
  160. }
  161. // CommunicationObject
  162. [MonoTODO]
  163. protected override void OnAbort ()
  164. {
  165. if (session != null)
  166. session.Close (TimeSpan.FromTicks (0));
  167. if (client != null)
  168. client.Close ();
  169. }
  170. protected override void OnClose (TimeSpan timeout)
  171. {
  172. if (session != null)
  173. session.Close (timeout);
  174. if (client != null)
  175. client.Close ();
  176. }
  177. protected override void OnOpen (TimeSpan timeout)
  178. {
  179. if (! is_service_side) {
  180. NetworkStream ns = client.GetStream ();
  181. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns, is_service_side) {
  182. Encoder = this.Encoder,
  183. Via = this.Via };
  184. frame.ProcessPreambleInitiator ();
  185. frame.ProcessPreambleAckInitiator ();
  186. } else {
  187. // server side
  188. Stream s = client.GetStream ();
  189. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  190. // FIXME: use retrieved record properties in the request processing.
  191. frame.ProcessPreambleRecipient ();
  192. frame.ProcessPreambleAckRecipient ();
  193. }
  194. }
  195. }
  196. }