1. Create a new project
RemotingInterface, and create a new Interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemotingInterface
{
/// <summary>
/// Remoting object interface
/// </summary>
public interface IRemotingObj
{
string Log(string message);
}
}
2. Create a new project
RemotingServer, and create a remoting object for work.
using System;
using System.IO;
using System.Text;
using RemotingInterface;
namespace RemotingServer
{
/// <summary>
/// Remoting object
/// </summary>
class RemotingObject : MarshalByRefObject, IRemotingObj
{
private string _FilePath = @"C:\remoting.txt";
/// <summary>
/// Log object created infomation.
/// </summary>
public RemotingObject()
{
string strMsg = "Object created.";
Console.WriteLine(strMsg);
File.AppendAllText(
_FilePath,
string.Format("{0}{2}{1}{2}", DateTime.Now, strMsg, Environment.NewLine),
Encoding.UTF8);
}
/// <summary>
/// Log recived message and display on console.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public string Log(string message)
{
DateTime dateNow = DateTime.Now;
Console.WriteLine(string.Format("{0} received : ", dateNow));
Console.WriteLine(message);
File.AppendAllText(
_FilePath,
string.Format("{0}{2}{1}{2}", dateNow, message, Environment.NewLine),
Encoding.UTF8);
return string.Format("{0} Logged.", dateNow);
}
}
}
3. Register service and start it.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
namespace RemotingServer
{
class Program
{
static void Main(string[] args)
{
// 建立通道
//TcpChannel tcpChannel = new TcpChannel(8888);
HttpChannel httpChannel = new HttpChannel(8889);
// 註冊監聽
//ChannelServices.RegisterChannel(tcpChannel, false);
ChannelServices.RegisterChannel(httpChannel, false);
// 註冊服務
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemotingServer.RemotingObject),
"RemotingSample",
WellKnownObjectMode.Singleton);
Console.Read();
}
}
}
4. Create a new project
RemotingClient for client testing.
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using RemotingInterface;
namespace RemotingClient
{
class Program
{
static void Main(string[] args)
{
HttpChannel httpChannel = new HttpChannel();
ChannelServices.RegisterChannel(httpChannel, false);
IRemotingObj remotingObj =
Activator.GetObject(
typeof(RemotingInterface.IRemotingObj),
"http://127.0.0.1:8889/RemotingSample") as IRemotingObj;
if (remotingObj == null)
{
Console.WriteLine("remoting object is null.");
Console.ReadLine();
}
else
{
while (true)
{
try
{
string strMsg = Console.ReadLine();
if (strMsg == "finish") return;
string strReturnMsg = remotingObj.Log(strMsg);
Console.WriteLine(strReturnMsg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
}