Friday, 7 September 2012

.Net Remoting Example


Define Interface  in Project1:

using System;

namespace IntTest
{
  public  interface iTest
    {
        String TestFun(String data);
    }
}

Define Class  in Project2(class library) :
using System;
using IntTest;

namespace clsLib
{

    public class clsMain : MarshalByRefObject,iTest
    {

        public string TestFun(String data)
        {
            return " From Server " + data;
        }
    }
}

Class must inherited from MarshalByRefObject apply remoting.
Web.Config in Project3(Win. service):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <service>
        <wellknown type="clsLib.clsMain, clsLib" objectUri="clsMain" mode="Singleton" />     
      </service>
      <channels>
        <channel displayName="TEst" ref="tcp" port="4040">
          <clientProviders>
            <formatter ref="binary" typeFilterLevel="Full" />
          </clientProviders>
          <serverProviders>
            <formatter ref="binary" typeFilterLevel="Full" />
            <formatter ref="soap" typeFilterLevel="Full" />
          </serverProviders>
        </channel>
      </channels>
    </application>
    <customErrors mode="Off"/>
  </system.runtime.remoting>
</configuration>

Service1.cs in Project3(win. Service):
using System;
using System.ServiceProcess;
using System.Threading;
using System.Runtime.Remoting;


namespace WinService
{
    public partial class Service1 : ServiceBase
    {
        AutoResetEvent ARE = new AutoResetEvent(false);
        public Service1()
        {
            RemotingConfiguration.Configure(@"D:\net class\Remoting  
                                           SAmple\TestRemoting\WinService\bin
                                           \Debug\WinService.exe.config",false);         
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Thread Th = new Thread(Test);
            Th.Start();
        }

        protected override void OnStop()
        {
        }
        public void Start()
        {
            OnStart(new string[] { });
        }

        /// <summary>
        /// Call this function from Program.cs
        /// </summary>
        public void Test()
        {
            while (true)
            {
                ARE.WaitOne();
            }
        }

    }
}



Now in Client Application :

using IntTest;
private void btnSend_Click(object sender, EventArgs e)
        {
            iTest instance = (iTest)Activator.GetObject(typeof(iTest),
                                           "tcp://" + Environment.MachineName + 
                                           ":4040/clsMain");
            txtRead.Text = instance.TestFun(txtSend.Text);
        }

No comments:

Post a Comment