Server.cs using System; using System.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels.HTTP;
namespace RemotingSample { public class Reverser : MarshalByRefObject { public string Reverse(string text) { Console.WriteLine("Reverse({0})", text);
string rev = "";
for (int i=text.Length-1; i>=0; i--) { rev += text[i]; }
Console.WriteLine("returning : {0}", rev);
return rev; } }
public class TheApp { public static void Main() { file:// Create a new HTTP channel that // listens on port 8000 HTTPChannel channel = new HTTPChannel(8000);
// Register the channel with the runtime ChannelServices.RegisterChannel(channel);
// Expose the Reverser object from this server RemotingServices.RegisterWellKnownType( "server", // assembly name "RemotingSample.Reverser", // full type name "Reverser.soap", file:// URI WellKnownObjectMode.Singleton // instancing mode );
// keep the server running until // the user presses enter Console.WriteLine("Server.exe"); Console.WriteLine("Press enter to stop server..."); Console.ReadLine(); } } }
现在我们已经拥有了一个字符反向服务,以下我们将建立一个客户应用来使用这个服务:
Client.cs using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels.HTTP; using RemotingSample; // reference the server
public class TheApp { public static void Main() { // Create and register a channel // to comunicate to the server. // The client will use port 8001 // to listen for callbacks HTTPChannel channel = new HTTPChannel(8001); ChannelServices.RegisterChannel(channel);
// create an instance on the remote server // and call a method remotely Reverser rev = (Reverser)Activator.GetObject( typeof(Reverser), // type to create "http://localhost:8000/Reverser.soap" file:// URI ); Console.WriteLine("Client.exe"); Console.WriteLine(rev.Reverse("Hello, World!")); } }
Soap.cs using System; using System.IO; using System.Runtime.Serialization.Formatters.Soap;
public class Person { public string FirstName = "David"; public string LastName = "Findley"; private int Age = 29; }
public class TheApp { public static void Main() { Stream stream = File.Create("example.xml"); SoapFormatter formatter = new SoapFormatter(); Person p = new Person();
// persist an integer formatter.Serialize(stream, 5);
file:// persist a string formatter.Serialize(stream, "This is a string");
// persist an object formatter.Serialize(stream, p);