下面給出了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(); } } } RemotingClient服務端代碼:
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(); } } } RemotingServer類庫代碼:
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:\remoting.txt", true, Encoding.Default)) { sw.Write(content + "\r\n"); } } } } RemotingObjects