C# - WCF services
Par Nicolas, jeudi 15 décembre 2011 à 05:05 :: geek stuff :: #501 :: rss
Define a service to expose logic.
Expose the interface to this logic at a certain endpoint, certain channel (in our case BasicHTTPBinding).
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using DM.PetShop; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // service relies on an implementation ServiceHost host = new ServiceHost(typeof(OrderService)); // service is exposed through the intreface (i.e. contract) host.AddServiceEndpoint(typeof(IOrderContract), new BasicHttpBinding(), "http://localhost:9000/PetShop"); // open the service ("fire and forget" call) host.Open(); // make sure the service doesn't die and print status Console.Title = String.Format("{0} is running ...", host.Description.Endpoints[0].Address); Console.Write("Server started. Press enter to stop..."); Console.ReadLine(); // close after receiving a keystroke host.Close(); Console.WriteLine("Server stoppped. Press enter to quit..."); Console.ReadLine(); } } }Here is the contract (a.k.a. interface) that will be exposed to the world
using System.ServiceModel; namespace DM.PetShop { [ServiceContract(Name = "PetShopOrderContract", Namespace = Constants.SERVICE_NAMESPACE)] public interface IOrderContract { [OperationContract(Name = "PlaceOrder", Action = "PlaceOrder", ReplyAction = "PlaceOrderReply")] void PlaceOrder(string orderData); } }Here the implementation (note the annotations,most important part)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace DM.PetShop { [ServiceBehavior(Name = "DM.PetShop.OrderService", Namespace = Constants.SERVICE_NAMESPACE)] public class OrderService : IOrderContract { public void PlaceOrder(string orderData) { Console.WriteLine("Diagnostic message !"); } } }Then write a client :
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Channels; using IOrderContractChannelFactory = System.ServiceModel.ChannelFactory; using DM.PetShop; namespace Project_Client1 { class Client1App { static void Main(string[] args) { IOrderContractChannelFactory factory = new IOrderContractChannelFactory(new BasicHttpBinding()); IOrderContract channel = factory.CreateChannel(new EndpointAddress("http://localhost:9000/PetShop/")); channel.PlaceOrder("1 parrot"); IClientChannel clientChannel = (IClientChannel)channel; try { if (clientChannel.State != CommunicationState.Closed) clientChannel.Close(); } catch { clientChannel.Abort(); } } } }
Commentaires
Aucun commentaire pour le moment.
Ajouter un commentaire
Les commentaires pour ce billet sont fermés.