1) Crie um projeto do tipo Class Library chamado Interfaces e dentro dele crie as interfaces IProduto, ICliente e IServico conforme abaixo:
//IProduto.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Interfaces
{
public interface IProduto
{
string GetProduto();
}
}
//ICliente.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Interfaces
{
public interface ICliente
{
string GetCliente();
}
}
//IServico.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Interfaces
{
public interface IServico
{
IProduto GetProduto();
ICliente GetCliente();
}
}
A dll gerada pelo projeto Interfaces será a única que existirá do lado do servidor cliente e servidor de negócio, isso garante que, todo o método disponível pelo Serviço ou pelas classes de negócio que ele retornará, estará disponível nos dois servidores.
2) Agora crie um projeto também do tipo Class Library chamado Business e crie as classes de negócio conforme abaixo:
//Produto.cs
using System;
using System.Collections.Generic;
using System.Text;
using Interfaces;
namespace Business
{
public class Produto : MarshalByRefObject, IProduto
{
public string GetProduto()
{
return "Computador";
}
}
}
//Cliente.cs
using System;
using System.Collections.Generic;
using System.Text;
using Interfaces;
namespace Business
{
public class Cliente : MarshalByRefObject, ICliente
{
#region ICliente Members
public string GetCliente()
{
return "Eduardo";
}
#endregion
}
}
//Servico.cs
using System;
using System.Collections.Generic;
using System.Text;
using Interfaces;
namespace Business
{
public class Servico: MarshalByRefObject, IServico
{
#region IServico Members
public IProduto GetProduto()
{
return new Produto();
}
public ICliente GetCliente()
{
return new Cliente();
}
#endregion
}
}
Veja que a função da interface IServico juntamente com a classe Servico é únicamente de retornar as classes de negócio Produto e Cliente.
3) Crie um projeto Console Application chamado Canal Remoting, neste projeto vamos registrar a classe Servico conforme abaixo:
//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Business;
namespace CanalRemoting
{
class Program
{
static void Main(string[] args)
{
// Create an instance of a channel
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel);
// Register as an available service with the name HelloWorld
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Business.Servico), "MyService",WellKnownObjectMode.SingleCall);
System.Console.WriteLine("Serviço Registrado, para sair pressione enter...");
System.Console.ReadLine();
}
}
}
4) Agora vamos criar o projeto que fará o papel da camada de interface com o usuário, crie um novo projeto do tipo Console Application com o nome Client.UI e copie o código abaixo:
//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Interfaces;
namespace Client.UI
{
class Program
{
static void Main(string[] args)
{
// Create a channel for communicating with the remote object
// Notice no port is specified on the client
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
// Create an instance of the remote object
IServico servico = (IServico)Activator.GetObject(typeof(IServico),"tcp://localhost:8080/MyService" );
IProduto objProduto = servico.GetProduto();
ICliente objCliente = servico.GetCliente();
// Use the object
if (objProduto.Equals(null))
{
System.Console.WriteLine(
"Error: unable to locate server");
}
else
{
Console.WriteLine(objProduto.GetProduto());
Console.WriteLine(objCliente.GetCliente());
}
System.Console.ReadLine();
}
}
}
Configure o Visual Studio para iniciar o projeto CanalRemoting e Client.UI simultaneamento, para isso clique com o botão direito sobre a solução no item Set Startup Projects ..., selecione a opção Multiple startup projects e atribua o Action Start para os projetos CanalRemoting e Client.UI, veja a figura:
Agora execute o projeto:
Considerações Finais
A aplicação acima é um exemplo bem simples de como utilizar o .Net Remoting como forma de comunicação.
Futuramente estarei abordando as questões que justificam a utilizam de vários servidores para sua aplicação.
Nenhum comentário:
Postar um comentário