Introdução
Este artigo é uma continuação do How to Receive
Messages from Desktop Application (Como receber mensagens do aplicativo
Desktop) e do How to Send Message to Desktop Application (Como enviar
mensagens para o aplicativo desktop) – disponíveis apenas em inglês – nos quais o aplicativo Silverlight se comunica
com o aplicativo autônomo .NET via TCP. Neste artigo, eu gostaria de mostrar
como implementar a comunicação via HTTP.
O exemplo abaixo
implementa um aplicativo .NET como serviço, e o aplicativo Silverlight como cliente.
O serviço escuta as mensagens de texto e
responde seu tamanho (VER ESTA TRADUÇÃO). O cliente então usa o serviço para obter o tamanho do
texto determinado.
A implementação usa o Eneter Messaging Framework. (Uma versão completa, grátis, não limitada e para uso não comercial do framework
pode ser baixada em http://www.eneter.net/. A ajuda online para
desenvolvedores pode ser encontrada em http://www.eneter.net/OnlineHelp/EneterMessagingFramework/Index.html.)
Segurança do Servidor
Da mesma maneira que a comunicação TCP, a comunicação HTTP requer o arquivo XML
com as regras de segurança. O Silverlight automaticamente solicita esse arquivo
quando o aplicativo quer se conectar a qualquer site que não seja o seu de
origem. No caso do HTTP, o Silverlight pede pelo arquivo com as regras de
segurança na raiz do pedido HTTP. Por exemplo, se o aplicativo Silverlight
requer http://127.0.0.1/MyHttpService/, o Silverlight irá
pedir pela segurança do servidor na raiz http://127.0.0.1/clientaccesspolicy.xml. Se o arquivo com as
regras de segurança não estiver disponível ou seu conteúdo não permitir a
comunicação, o pedido do HTTP não será atendido.

Aplicação de Serviço
A aplicação de serviço fornece o serviço de segurança HTTP para a comunicação
com o cliente Silverlight. Ele então implementa o simples serviço de calcular
o comprimento do texto dado.
Por favor note que
para executar um aplicativo de escuta HTTP, você deve executá-lo sob direitos
do usuário suficientes. Caso contrário
você terá uma exceção.
Toda a implementação é muito simples.
using System;
using Eneter.Messaging.EndPoints.TypedMessages;
using Eneter.Messaging.MessagingSystems.HttpMessagingSystem;
using Eneter.Messaging.MessagingSystems.MessagingSystemBase;
namespace LengthService
{
class Program
{
// Receiver receiving messages of type string and responding int.
static private IDuplexTypedMessageReceiver<int, string> myReceiver;
static void Main(string[] args)
{
// Start Http Policy Server
// Note: Http policy server must be initialized to the root.
HttpPolicyServer aPolicyServer = new HttpPolicyServer("http://127.0.0.1:8034/");
aPolicyServer.StartPolicyServer();
Console.WriteLine("Http Policy Server is running.");
// Create Http messaging.
IMessagingSystemFactory aMessaging = new HttpMessagingSystemFactory();
// Create the input channel that is able to
// receive messages and send back response messages.
IDuplexInputChannel anInputChannel =
aMessaging.CreateDuplexInputChannel("http://127.0.0.1:8034/MyService/");
// Create message receiver - response sender.
// It receives 'string' and responses 'int'.
IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory();
myReceiver = aSenderFactory.CreateDuplexTypedMessageReceiver<int, string>();
myReceiver.MessageReceived += OnMessageReceived;
Console.WriteLine("The service is listening to Http.");
Console.WriteLine("Press Enter to stop the service.n");
// Attach the duplex input channel and start listening.
myReceiver.AttachDuplexInputChannel(anInputChannel);
Console.ReadLine();
myReceiver.DetachDuplexInputChannel();
aPolicyServer.StopPolicyServer();
}
static private void OnMessageReceived(object sender,
TypedRequestReceivedEventArgs<string> e)
{
if (e.ReceivingError == null)
{
int aLength = e.RequestMessage.Length;
Console.WriteLine("Received string: {0}; Responded length: {1}",
e.RequestMessage, aLength);
// Response the length of the string.
myReceiver.SendResponseMessage(e.ResponseReceiverId, aLength);
}
}
}
}
Aplicação do Cliente Silverlight
A aplicação do cliente usa o serviço para obter o comprimento do texto dado. A aplicação do
cliente usa a montagem construída para o Silverlight, Eneter.Messaging.Framework.Silverlight.dll.
A implementação é muito simples.
using System.Windows;
using System.Windows.Controls;
using Eneter.Messaging.EndPoints.TypedMessages;
using Eneter.Messaging.MessagingSystems.HttpMessagingSystem;
using Eneter.Messaging.MessagingSystems.MessagingSystemBase;
namespace LengthClient
{
public partial class MainPage : UserControl
{
// Sender sending messages of type string and
// receiving responses of type int.
private IDuplexTypedMessageSender<int, string> mySender;
public MainPage()
{
InitializeComponent();
OpenConnection();
}
private void OpenConnection()
{
// Create HTTP messaging with default parameters.
// Note: The default constructor routes received response
// messages into the Silverlight thread.
// If it is not desired, then it can be changed.
IMessagingSystemFactory aMessaging = new HttpMessagingSystemFactory();
IDuplexOutputChannel anOutputChannel =
aMessaging.CreateDuplexOutputChannel("http://127.0.0.1:8034/MyService/");
// Create message sender - response receiver.
IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory();
mySender = aSenderFactory.CreateDuplexTypedMessageSender<int, string>();
mySender.ResponseReceived += OnResponseReceived;
// Attach duplex output channel and be able to send messages
// and receive response messages.
mySender.AttachDuplexOutputChannel(anOutputChannel);
}
private void UserControl_Unloaded(object sender, RoutedEventArgs e)
{
mySender.DetachDuplexOutputChannel();
}
private void GetLengthButton_Click(object sender, RoutedEventArgs e)
{
// Send the user text to the service.
// Service will response the length of the text.
mySender.SendRequestMessage(UserText.Text);
}
private void OnResponseReceived(object sender, TypedResponseReceivedEventArgs<int> e)
{
if (e.ReceivingError == null)
{
int aResult = e.ResponseMessage;
// Display the response message.
// The response message is the length of the text.
ReceivedLength.Text = aResult.ToString();
}
}
}
}
E aqui estão as aplicações de comunicação:

Espero que tenha achado este artigo útil.
?
Texto original disponível em http://eneter.blogspot.com/2011/04/silverlight-how-to-communicate-with.html#more







