TcpDuplexSessionChannel.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. if (timeout <= TimeSpan.Zero)
  121. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  122. if (!is_service_side) {
  123. if (message.Headers.To == null)
  124. message.Headers.To = RemoteAddress.Uri;
  125. if (message.Headers.ReplyTo == null)
  126. message.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
  127. } else {
  128. if (message.Headers.RelatesTo == null)
  129. message.Headers.RelatesTo = OperationContext.Current.IncomingMessageHeaders.MessageId;
  130. }
  131. client.SendTimeout = (int) timeout.TotalMilliseconds;
  132. frame.WriteSizedMessage (message);
  133. // FIXME: should EndRecord be sent here?
  134. //if (is_service_side && client.Available > 0)
  135. // frame.ProcessEndRecordRecipient ();
  136. }
  137. public override Message Receive ()
  138. {
  139. return Receive (DefaultReceiveTimeout);
  140. }
  141. public override Message Receive (TimeSpan timeout)
  142. {
  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. if (client.Available > 0)
  167. return true;
  168. DateTime start = DateTime.Now;
  169. do {
  170. Thread.Sleep (50);
  171. if (client.Available > 0)
  172. return true;
  173. } while (DateTime.Now - start < timeout);
  174. return false;
  175. }
  176. // CommunicationObject
  177. [MonoTODO]
  178. protected override void OnAbort ()
  179. {
  180. if (!is_service_side)
  181. if (session != null)
  182. session.Close (TimeSpan.FromTicks (0));
  183. if (client != null)
  184. client.Close ();
  185. }
  186. protected override void OnClose (TimeSpan timeout)
  187. {
  188. if (!is_service_side)
  189. if (session != null)
  190. session.Close (timeout);
  191. if (client != null)
  192. client.Close ();
  193. }
  194. protected override void OnOpen (TimeSpan timeout)
  195. {
  196. if (! is_service_side) {
  197. NetworkStream ns = client.GetStream ();
  198. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns, is_service_side) {
  199. Encoder = this.Encoder,
  200. Via = this.Via };
  201. frame.ProcessPreambleInitiator ();
  202. frame.ProcessPreambleAckInitiator ();
  203. } else {
  204. // server side
  205. Stream s = client.GetStream ();
  206. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  207. // FIXME: use retrieved record properties in the request processing.
  208. frame.ProcessPreambleRecipient ();
  209. frame.ProcessPreambleAckRecipient ();
  210. }
  211. }
  212. class MyBinaryWriter : BinaryWriter
  213. {
  214. public MyBinaryWriter (Stream s)
  215. : base (s)
  216. {
  217. }
  218. public void WriteBytes (byte [] bytes)
  219. {
  220. Write7BitEncodedInt (bytes.Length);
  221. Write (bytes);
  222. }
  223. }
  224. }
  225. }