日期:2013-06-26  浏览次数:20560 次

 以下我们将举一个使用channel的例子。在这个例子中,我们将可以看到使用HTTP channel把两个应用<br>
连接在一起是如此的简单。以下的服务器应用提供了一个服务,可将一个字符串的字母顺序反转。<br>
<br>
  Server.cs using System;<br>
  using System.IO;<br>
  using System.Runtime.Remoting;<br>
  using System.Runtime.Remoting.Channels.HTTP;<br>
<br>
  namespace RemotingSample <br>
  {<br>
   public class Reverser : MarshalByRefObject<br>
   {<br>
    public string Reverse(string text)<br>
    {<br>
     Console.WriteLine("Reverse({0})", text);<br>
<br>
     string rev = "";<br>
<br>
     for (int i=text.Length-1; i>=0; i--)<br>
     {<br>
      rev += text[i];<br>
      }<br>
<br>
     Console.WriteLine("returning : {0}", rev);<br>
<br>
     return rev;<br>
    }<br>
   }<br>
<br>
   public class TheApp<br>
   {<br>
    public static void Main()<br>
    {<br>
     file://<font color=#FF0000> Create a new HTTP channel that</font><br>
     // <font color=#FF0000>listens on port 8000</font><br>
     HTTPChannel channel = new HTTPChannel(8000);<br>
<br>
     // <font color=#FF0000>Register the channel with the runtime</font><br>
     ChannelServices.RegisterChannel(channel);<br>
<br>
     // <font color=#FF0000>Expose the Reverser object from this server</font><br>
     RemotingServices.RegisterWellKnownType(<br>
         "server", // <font color=#FF0000>assembly name</font><br>
         "RemotingSample.Reverser", // <font color=#FF0000>full type name</font><br>
         "Reverser.soap", file://<font color=#FF0000> URI</font><br>
         WellKnownObjectMode.Singleton // <font color=#FF0000>instancing mode</font><br>
      );<br>
<br>
     // <font color=#FF0000>keep the server running until</font><br>
     // <font color=#FF0000>the user presses enter</font><br>
     Console.WriteLine("Server.exe");<br>
     Console.WriteLine("Press enter to stop server...");<br>
     Console.ReadLine();<br>
    }<br>
   }<br>
  }<br>
<br>
  现在我们已经拥有了一个字符反向服务,以下我们将建立一个客户应用来使用这个服务:<br>
<br>
   Client.cs using System;<br>
   using System.Runtime.Remoting;<br>
   using System.Runtime.Remoting.Channels.HTTP;<br>
   using RemotingSample; // reference the server<br>
<br>
   public class TheApp<br>
    {<br>
     public static void Main()<br>
     {<br>
      // <font color=#FF0000>Create and register a channel</font><br>
      // <font color=#FF0000>to comunicate to the server.</font><br>
      // <font color=#FF0000>The client will use port 8001</font><br>
      // <font color=#FF0000>to listen for callbacks</font><br>
      HTTPChannel channel = new HTTPChannel(8001);<br>
      ChannelServices.RegisterChannel(channel);<br>
<br>
      // <font color=#FF0000>create an instance on the remote server</font><br>
      // <font color=#FF0000>and call a method remotely</font><br>
      Reverser rev = (Reverser)Activator.GetObject(<br>
         typeof(Reverser), // <font color=#FF0000>type to create</font><br>
         "http://localhost:8000/Reverser.soap" file://<f