internal static IChannelListener CreateChannelListener <TChannel>(TransportBindingElement transport) where TChannel : class, IChannel { Binding binding = new CustomBinding(transport); return(binding.BuildChannelListener <TChannel>()); }
static void Main(string[] args) { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); IChannelListener<IReplyChannel> listener=binding.BuildChannelListener<IReplyChannel>(new Uri("http://localhost:9090/RequestReplyService"),new BindingParameterCollection()); listener.Open(); IReplyChannel replyChannel = listener.AcceptChannel(); replyChannel.Open(); Console.WriteLine("starting to receive message...."); RequestContext requestContext = replyChannel.ReceiveRequest(); Console.WriteLine("Received a Message, action:{0},body:{1}", requestContext.RequestMessage.Headers.Action, requestContext.RequestMessage.GetBody<string>()); Message message = Message.CreateMessage(binding.MessageVersion, "response", "response Message"); requestContext.Reply(message); requestContext.Close(); replyChannel.Close(); listener.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
private static void CreateHttpGetChannelDispatcher(ServiceHostBase host, Uri listenUri, MetadataSet metadata) { //创建Binding TextMessageEncodingBindingElement messageEncodingElement = new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.None }; HttpTransportBindingElement transportElement = new HttpTransportBindingElement(); Utility.SetPropertyValue(transportElement, "Method", "GET"); Binding binding = new CustomBinding(messageEncodingElement, transportElement); //创建ChannelListener IChannelListener listener = binding.BuildChannelListener<IReplyChannel>(listenUri, string.Empty, ListenUriMode.Explicit, new BindingParameterCollection()); ChannelDispatcher dispatcher = new ChannelDispatcher(listener, "ServiceMetadataBehaviorHttpGetBinding", binding) { MessageVersion = binding.MessageVersion }; //创建EndpointDispatcher EndpointDispatcher endpoint = new EndpointDispatcher(new EndpointAddress(listenUri), "IHttpGetMetadata", "http://www.artech.com/"); //创建DispatchOperation,并设置DispatchMessageFormatter和OperationInvoker DispatchOperation operation = new DispatchOperation(endpoint.DispatchRuntime, "Get", "*", "*"); operation.Formatter = Utility.CreateInstance<IDispatchMessageFormatter>(MessageOperationFormatterType, Type.EmptyTypes, new object[0]); MethodInfo method = typeof(IHttpGetMetadata).GetMethod("Get"); operation.Invoker = Utility.CreateInstance<IOperationInvoker>(SyncMethodInvokerType, new Type[] { typeof(MethodInfo) }, new object[] { method }); endpoint.DispatchRuntime.Operations.Add(operation); //设置SingletonInstanceContext和InstanceContextProvider MetadataProvisionService serviceInstance = new MetadataProvisionService(metadata); endpoint.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, serviceInstance); endpoint.DispatchRuntime.InstanceContextProvider = Utility.CreateInstance<IInstanceContextProvider>(SingletonInstanceContextProviderType, new Type[] { typeof(DispatchRuntime) }, new object[] { endpoint.DispatchRuntime }); dispatcher.Endpoints.Add(endpoint); //设置ContractFilter和AddressFilter endpoint.ContractFilter = new MatchAllMessageFilter(); endpoint.AddressFilter = new MatchAllMessageFilter(); host.ChannelDispatchers.Add(dispatcher); }
public static void Main () { CustomBinding binding = new CustomBinding (); binding.Elements.Add (new TextMessageEncodingBindingElement ()); binding.Elements.Add (new TcpTransportBindingElement ()); BindingParameterCollection bpcol = new BindingParameterCollection (); // using (IChannelListener<IDuplexSessionChannel> listener = // binding.BuildChannelListener<IDuplexSessionChannel> ( // new Uri ("net.tcp://localhost/Server"), bpcol)) // { IChannelListener<IDuplexSessionChannel> listener = binding.BuildChannelListener<IDuplexSessionChannel> ( new Uri ("net.tcp://localhost/"), bpcol); listener.Open (); IDuplexSessionChannel channel = listener.AcceptChannel (); Console.WriteLine ("Listening for messages..."); channel.Open (); Message message = channel.Receive (); Console.WriteLine ("Message received."); Console.WriteLine ("Message action: {0}", message.Headers.Action); Console.WriteLine ("Message content: {0}", message.GetBody<string> ()); message = Message.CreateMessage ( //channel.Manager.MessageVersion, MessageVersion.Default, "Action", "Hello, World, from service side"); channel.Send (message); message.Close (); channel.Close (); listener.Close (); // } }
public async Task StartAsync() { if (listener != null) { throw new InvalidOperationException(ExceptionMessageListenerHasAlreadyBeenStarted); } try { var tcpRelayTransportBindingElement = new TcpRelayTransportBindingElement(RelayClientAuthenticationType.RelayAccessToken) { TransferMode = TransferMode.Buffered, ConnectionMode = TcpRelayConnectionMode.Relayed, IsDynamic = (relayAddressType == RelayAddressType.Dynamic), ManualAddressing = true }; tcpRelayTransportBindingElement.GetType() .GetProperty("TransportProtectionEnabled", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(tcpRelayTransportBindingElement, true); var tb = new TransportClientEndpointBehavior(tokenProvider); this.listenerBinding = new CustomBinding( new BinaryMessageEncodingBindingElement(), tcpRelayTransportBindingElement); listener = listenerBinding.BuildChannelListener<IDuplexSessionChannel>(new Uri(address), tb); await Task.Factory.FromAsync(listener.BeginOpen, listener.EndOpen, null); } catch { listener = null; throw; } }
public void ServiceRecipientHasNoKeys () { AsymmetricSecurityBindingElement sbe = new AsymmetricSecurityBindingElement (); sbe.InitiatorTokenParameters = new X509SecurityTokenParameters (); sbe.RecipientTokenParameters = new UserNameSecurityTokenParameters (); //sbe.SetKeyDerivation (false); //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt; CustomBinding binding = new CustomBinding (sbe, new HttpTransportBindingElement ()); IChannelListener<IReplyChannel> l = binding.BuildChannelListener<IReplyChannel> (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), new BindingParameterCollection ()); try { l.Open (); } finally { if (l.State == CommunicationState.Opened) l.Close (); } }
public void CheckDuplicateAuthenticatorTypesService () { SymmetricSecurityBindingElement be = new SymmetricSecurityBindingElement (); be.ProtectionTokenParameters = new X509SecurityTokenParameters (); be.EndpointSupportingTokenParameters.Endorsing.Add ( new X509SecurityTokenParameters ()); // This causes multiple supporting token authenticator // of the same type. be.OptionalEndpointSupportingTokenParameters.Endorsing.Add ( new X509SecurityTokenParameters ()); Binding b = new CustomBinding (be, new HttpTransportBindingElement ()); ServiceCredentials cred = new ServiceCredentials (); cred.ServiceCertificate.Certificate = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); IChannelListener<IReplyChannel> ch = b.BuildChannelListener<IReplyChannel> (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), cred); try { ch.Open (); } finally { if (ch.State == CommunicationState.Closed) ch.Close (); } }
public void BuildListenerWithoutProtectionTokenParameters () { CustomBinding b = new CustomBinding ( new SymmetricSecurityBindingElement (), new TextMessageEncodingBindingElement (), new HttpTransportBindingElement ()); b.BuildChannelListener<IReplyChannel> (new BindingParameterCollection ()); }
void AddMetadataEndpoint(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher, bool debugMode) { Uri baseAddress = endpoint.Address.Uri; if (baseAddress == null) { return; } ServiceHostBase host = endpointDispatcher.ChannelDispatcher.Host; UriBuilder builder = new UriBuilder(baseAddress); builder.Path += builder.Path.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? (WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode)) : ("/" + WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode)); EndpointAddress metadataAddress = new EndpointAddress(builder.Uri); foreach (ServiceEndpoint serviceEndpoint in host.Description.Endpoints) { if (EndpointAddress.UriEquals(serviceEndpoint.Address.Uri, metadataAddress.Uri, true, false))// ignoreCase // includeHostNameInComparison { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR2.GetString(SR2.JsonNoEndpointAtMetadataAddress, this.GetType().ToString(), serviceEndpoint.Address, serviceEndpoint.Name, host.Description.Name))); } } HttpTransportBindingElement transportBindingElement; HttpTransportBindingElement existingTransportBindingElement = endpoint.Binding.CreateBindingElements().Find<HttpTransportBindingElement>(); if (existingTransportBindingElement != null) { transportBindingElement = (HttpTransportBindingElement)existingTransportBindingElement.Clone(); } else { if (baseAddress.Scheme == "https") { transportBindingElement = new HttpsTransportBindingElement(); } else { transportBindingElement = new HttpTransportBindingElement(); } } transportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; transportBindingElement.TransferMode = TransferMode.Buffered; transportBindingElement.MaxBufferSize = MaxMetadataEndpointBufferSize; transportBindingElement.MaxReceivedMessageSize = MaxMetadataEndpointBufferSize; Binding metadataBinding = new CustomBinding( new WebScriptMetadataMessageEncodingBindingElement(), transportBindingElement); BindingParameterCollection parameters = host.GetBindingParameters(endpoint); // build endpoint dispatcher ContractDescription metadataContract = ContractDescription.GetContract(typeof(ServiceMetadataExtension.IHttpGetMetadata)); OperationDescription metadataOperation = metadataContract.Operations[0]; EndpointDispatcher metadataEndpointDispatcher = new EndpointDispatcher(metadataAddress, metadataContract.Name, metadataContract.Namespace); DispatchOperation dispatchOperation = new DispatchOperation(metadataEndpointDispatcher.DispatchRuntime, metadataOperation.Name, metadataOperation.Messages[0].Action, metadataOperation.Messages[1].Action); dispatchOperation.Formatter = new WebScriptMetadataFormatter(); dispatchOperation.Invoker = new SyncMethodInvoker(metadataOperation.SyncMethod); metadataEndpointDispatcher.DispatchRuntime.Operations.Add(dispatchOperation); metadataEndpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, new WebScriptClientGenerator(endpoint, debugMode, !String.IsNullOrEmpty(this.JavascriptCallbackParameterName))); metadataEndpointDispatcher.DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider(metadataEndpointDispatcher.DispatchRuntime); // build channel dispatcher IChannelListener<IReplyChannel> listener = null; if (metadataBinding.CanBuildChannelListener<IReplyChannel>(parameters)) { listener = metadataBinding.BuildChannelListener<IReplyChannel>(metadataAddress.Uri, parameters); } ChannelDispatcher metadataChannelDispatcher = new ChannelDispatcher(listener); metadataChannelDispatcher.MessageVersion = MessageVersion.None; metadataChannelDispatcher.Endpoints.Add(metadataEndpointDispatcher); host.ChannelDispatchers.Add(metadataChannelDispatcher); }
public void CustomTransportDoesNotRequireMessageEncoding () { ReplyHandler replier = delegate (Message msg) { resmsg = msg; }; RequestReceiver receiver = delegate () { return reqmsg; }; RequestSender sender = delegate (Message msg) { reqmsg = msg; CustomBinding br = new CustomBinding ( new HandlerTransportBindingElement (replier, receiver)); IChannelListener<IReplyChannel> l = br.BuildChannelListener<IReplyChannel> ( new BindingParameterCollection ()); l.Open (); IReplyChannel rch = l.AcceptChannel (); rch.Open (); Message res = Message.CreateMessage (MessageVersion.Default, "urn:succeeded"); rch.ReceiveRequest ().Reply (res); rch.Close (); l.Close (); return resmsg; }; CustomBinding bs = new CustomBinding ( new HandlerTransportBindingElement (sender)); IChannelFactory<IRequestChannel> f = bs.BuildChannelFactory<IRequestChannel> ( new BindingParameterCollection ()); f.Open (); IRequestChannel ch = f.CreateChannel (new EndpointAddress ("urn:dummy")); ch.Open (); Message result = ch.Request (Message.CreateMessage (MessageVersion.Default, "urn:request")); }
internal static IChannelListener CreateChannelListener <TChannel>(TransportBindingElement transport) where TChannel : class, IChannel { System.ServiceModel.Channels.Binding binding = new CustomBinding(new BindingElement[] { transport }); return(binding.BuildChannelListener <TChannel>(new object[0])); }