Remoting is a technology that helps
you to communicate between different applications regardless of whether they
reside on the same computer or on different computers. Even these applications
can have different operation systems.
Remoting needs:
1. A server object that expose the
functionality to callers outside its boundary
2. A client that makes calls to the
server object
3. A transportation mechanism to
pass the calls from one end to the other
Developing a sample for .Net Remote Communication:
Create a Remotable Object:
A remotable object is an object that inherits from
MarshalByRefObject
.
Create a new C# class library project. Add a class called Test
, and put in the following code. Add a reference to System.Runtime.Remoting
in the project, otherwise the TcpChannel
will not be found. Compile the class to make sure you have everything correct.Please follow these steps to write a Remoting code:
1- Create a class library name it Service : in class library you just have a class named Test
namespace Service
{
public class Test:MarshalByRefObject
{
public Test()
{
Console.WriteLine("New Object!");
}
public string PrintYourAddress()
{
string myaddress = AppDomain.CurrentDomain.BaseDirectory;
Console.WriteLine("This is myaddress " + myaddress);
return myaddress;
}
public void WriteInServer()
{
Console.WriteLine("I wrote time in server " + DateTime.Now.ToShortTimeString());
}
}
}
2- Create a console application name it Server: you
have to write some code in Main method. You need to add
System.Runtime.Remoting to your references. Furthermore you need to add
Service library to this project.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
namespace Server
{
class Program
{
static void Main(string[] args)
{
HttpChannel ch = new HttpChannel(4000);
ChannelServices.RegisterChannel(ch);
//because this is written in server so we need to use Service type methods
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Service.Test), "ServiceURI", WellKnownObjectMode.Singleton);
Console.WriteLine("Server is Started...");
Console.ReadLine();
}
}
}
3- Create
a windows application name it Client: First of all you need to add
reference service. Add two buttons and in button clicks add these code
also you need to add some code in FormLoad event
Test t;
private void Form1_Load(object sender, EventArgs e)
{
RemotingConfiguration.RegisterWellKnownClientType(typeof(Test), "http://localhost:4000/ServiceURI");
t= new Test();
}
private void button1_Click(object sender, EventArgs e)
{
t.WriteInServer();
}
private void button2_Click(object sender, EventArgs e)
{
string str = t.PrintYourAddress();
MessageBox.Show(str);
}
No comments:
Post a Comment