下面给出了Remoting的小实例,主要功能是将客户端的数据写入到服务端。
分析图:
程序代码为2个控制台应用程序(1个客户端,1个服务器端)和1个类库,如下所示。
客户端代码:
using RemotingObjects; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Text; namespace RemotingClient { class Program { static void Main(string[] args) { TcpChannel channel = new TcpChannel(); ChannelServices.RegisterChannel(channel, false); WriteFileToLocal wfobj = (WriteFileToLocal)Activator.GetObject(typeof(RemotingObjects.Process), "tcp://localhost:8085/RemotingWriteFileToLocalService"); if (wfobj == null) { Console.WriteLine("Couldn't create Remoting Object 'WriteFileToLocal'."); } else { Console.WriteLine("Please enter content:"); String name = Console.ReadLine(); try { wfobj.write(name); } catch (System.Net.Sockets.SocketException e) { Console.WriteLine(e.ToString()); } } Console.Read(); } } }
服务端代码:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Text; namespace RemotingServer { class Program { static void Main(string[] args) { TcpChannel channel = new TcpChannel(8085); ChannelServices.RegisterChannel(channel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObjects.Process), "RemotingWriteFileToLocalService", WellKnownObjectMode.SingleCall); Console.WriteLine("Server:Press Enter key to exit"); Console.ReadLine(); } } }
类库代码:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace RemotingObjects { public interface WriteFileToLocal { void write(string content); } public class Process : MarshalByRefObject, WriteFileToLocal { public Process() { Console.WriteLine("Write Starting..."); } /// <summary> /// 写文件 /// </summary> /// <param name="content">写入文件的内容</param> public void write(string content) { using (StreamWriter sw = new StreamWriter(@"D: emoting.txt", true, Encoding.Default)) { sw.Write(content + " "); } } } }