static void Main(string[] args) { try { //使用说明先启动input,然后在启动启动output。 //记得使用管理员启动VS,我在程序清单中添加了管理员权限。 //创建自定义通道 BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码 bindingElements[1] = new HttpTransportBindingElement(); //Htp传输 CustomBinding binding = new CustomBinding(bindingElements); using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body")) { //创建ChannelFactory request 请求 reply回复 IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); //打开ChannelFactory //这里创建IRequestChannel IRequestChannel requestChannel = factory.CreateChannel(new System.ServiceModel.EndpointAddress("http://localhost:9090/RequestReplyService")); requestChannel.Open(); //打开通道 Message response = requestChannel.Request(message); //发送消息 Console.WriteLine("已经成功发送消息!"); //查看返回消息 Console.WriteLine($"接收到一条返回消息,action为:{response.Headers.Action},body为{response.GetBody<String>()}"); requestChannel.Close(); //关闭通道 factory.Close(); //关闭工厂 } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
//入口方法 static void Main(string[] args) { try { //建立自定义的通道栈 BindingElement[] bindingElements = new BindingElement[3]; bindingElements[0] = new TextMessageEncodingBindingElement(); //OneWayBindingElement可以使得传输通道支持数据报模式 bindingElements[1] = new OneWayBindingElement(); bindingElements[2] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body")) { //创建ChannelFactory IChannelFactory <IOutputChannel> factory = binding.BuildChannelFactory <IOutputChannel>(new BindingParameterCollection()); factory.Open(); //这里创建IOutputChannel IOutputChannel outputChannel = factory.CreateChannel(new EndpointAddress("http://localhost/InputService")); outputChannel.Open(); //发送消息 outputChannel.Send(message); Console.WriteLine("已经成功发送消息!"); outputChannel.Close(); factory.Close(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
public async Task <RelayConnection> ConnectAsync() { var tb = new TransportClientEndpointBehavior(tokenProvider); var bindingElement = new TcpRelayTransportBindingElement( RelayClientAuthenticationType.RelayAccessToken) { TransferMode = TransferMode.Buffered, ConnectionMode = TcpRelayConnectionMode.Relayed, ManualAddressing = true }; bindingElement.GetType() .GetProperty("TransportProtectionEnabled", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(bindingElement, true); var rt = new CustomBinding( new BinaryMessageEncodingBindingElement(), bindingElement); var cf = rt.BuildChannelFactory <IDuplexSessionChannel>(tb); await Task.Factory.FromAsync(cf.BeginOpen, cf.EndOpen, null); var ch = cf.CreateChannel(new EndpointAddress(address)); await Task.Factory.FromAsync(ch.BeginOpen, ch.EndOpen, null); return(new RelayConnection(ch) { WriteTimeout = (int)rt.SendTimeout.TotalMilliseconds, ReadTimeout = (int)rt.ReceiveTimeout.TotalMilliseconds }); }
private static NetworkDetector.ConnectivityStatus CheckTcpConnectivity(Uri baseAddress, out Exception exception) { NetworkDetector.ConnectivityStatus connectivityStatu = NetworkDetector.ConnectivityStatus.Unavailable; exception = null; if (!RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTP", false) && !RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTPS", false)) { try { BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement(); TcpTransportBindingElement tcpTransportBindingElement = new TcpTransportBindingElement(); tcpTransportBindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 100; tcpTransportBindingElement.MaxReceivedMessageSize = (long)65536; CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(binaryMessageEncodingBindingElement); customBinding.Elements.Add(tcpTransportBindingElement); customBinding.OpenTimeout = TimeSpan.FromSeconds(10); customBinding.SendTimeout = TimeSpan.FromSeconds(10); customBinding.ReceiveTimeout = TimeSpan.MaxValue; int num = 9350; Uri uri = ServiceBusUriHelper.CreateServiceUri("net.tcp", string.Concat(baseAddress.DnsSafeHost, ":", num.ToString(CultureInfo.InvariantCulture)), "/"); IChannelFactory <IDuplexSessionChannel> channelFactory = null; IDuplexSessionChannel duplexSessionChannel = null; try { channelFactory = customBinding.BuildChannelFactory <IDuplexSessionChannel>(new object[0]); channelFactory.Open(); duplexSessionChannel = channelFactory.CreateChannel(new EndpointAddress(uri, new AddressHeader[0])); duplexSessionChannel.Open(); Message message = Message.CreateMessage(MessageVersion.Default, "http://schemas.microsoft.com/netservices/2009/05/servicebus/connect/OnewayPing", new OnewayPingMessage()); duplexSessionChannel.Send(message, customBinding.SendTimeout); duplexSessionChannel.Close(); duplexSessionChannel = null; channelFactory.Close(); channelFactory = null; } finally { if (duplexSessionChannel != null) { duplexSessionChannel.Abort(); } if (channelFactory != null) { channelFactory.Abort(); } } connectivityStatu = NetworkDetector.ConnectivityStatus.Available; } catch (CommunicationException communicationException) { exception = communicationException; } catch (TimeoutException timeoutException) { exception = timeoutException; } } NetworkDetector.LogResult(baseAddress, "Tcp", connectivityStatu); return(connectivityStatu); }
IChannelFactory <IRequestChannel> CreateDefaultServiceCertFactory() { CustomBinding b = CreateBinding(delegate(Message req) { return(null); }); ClientCredentials cred = new ClientCredentials(); cred.ServiceCertificate.DefaultCertificate = new X509Certificate2("Test/Resources/test.pfx", "mono"); BindingParameterCollection parameters = new BindingParameterCollection(); parameters.Add(cred); ChannelProtectionRequirements cp = new ChannelProtectionRequirements(); cp.IncomingSignatureParts.AddParts( new MessagePartSpecification(true), "http://tempuri.org/MyAction"); cp.IncomingEncryptionParts.AddParts( new MessagePartSpecification(true), "http://tempuri.org/MyAction"); parameters.Add(cp); return(b.BuildChannelFactory <IRequestChannel> (parameters)); }
public void OpenRequestNonAuthenticatable() { SymmetricSecurityBindingElement sbe = new SymmetricSecurityBindingElement(); sbe.ProtectionTokenParameters = new UserNameSecurityTokenParameters(); Binding binding = new CustomBinding(sbe, new HandlerTransportBindingElement(null)); BindingParameterCollection pl = new BindingParameterCollection(); ClientCredentials cred = new ClientCredentials(); cred.UserName.UserName = "******"; pl.Add(cred); IChannelFactory <IRequestChannel> f = binding.BuildChannelFactory <IRequestChannel> (pl); f.Open(); IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy")); try { ch.Open(); Assert.Fail("NotSupportedException is expected."); } catch (NotSupportedException) { } }
public void SendRequestWithoutSignatureMessagePart() { CustomBinding b = CreateBinding(); // without ChannelProtectionRequirements it won't be // signed and/or encrypted. IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.Open(); IRequestChannel ch = f.CreateChannel(CreateX509EndpointAddress("stream:dummy")); ch.Open(); // MessageSecurityException : No signature message parts // were specified for messages with the 'myAction' // action. try { ch.Request(Message.CreateMessage(b.MessageVersion, "myAction")); Assert.Fail("MessageSecurityException is expected here."); } catch (MessageSecurityException) { } }
private IChannelFactory <IRequestSessionChannel> CreateChannelFactory(bool useSslStreamSecurity, bool includeExceptionDetails, DnsEndpointIdentity endpointIdentity) { string str; int num = 0; CustomBinding customBinding = SbmpProtocolDefaults.CreateBinding(false, false, 2147483647, useSslStreamSecurity, endpointIdentity); DuplexRequestBindingElement duplexRequestBindingElement = new DuplexRequestBindingElement() { IncludeExceptionDetails = includeExceptionDetails, ClientMode = this.clientMode }; DuplexRequestBindingElement duplexRequestBindingElement1 = duplexRequestBindingElement; int num1 = num; num = num1 + 1; customBinding.Elements.Insert(num1, duplexRequestBindingElement1); BindingParameterCollection bindingParameterCollection = new BindingParameterCollection(); if (useSslStreamSecurity) { ClientCredentials clientCredential = new ClientCredentials(); clientCredential.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; clientCredential.ServiceCertificate.Authentication.CustomCertificateValidator = RetriableCertificateValidator.Instance; if (SoapProtocolDefaults.IsAvailableClientCertificateThumbprint(out str)) { clientCredential.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, str); } bindingParameterCollection.Add(clientCredential); } this.MessageVersion = customBinding.MessageVersion; return(customBinding.BuildChannelFactory <IRequestSessionChannel>(bindingParameterCollection)); }
public void CheckDuplicateAuthenticatorTypesClient() { 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()); ClientCredentials cred = new ClientCredentials(); cred.ClientCertificate.Certificate = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono"); IChannelFactory <IReplyChannel> ch = b.BuildChannelFactory <IReplyChannel> (new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), cred); try { ch.Open(); } finally { if (ch.State == CommunicationState.Closed) { ch.Close(); } } }
public static void Snippet3() { // <Snippet3> CustomBinding binding = new CustomBinding(); binding.Elements.Add(new HttpTransportBindingElement()); Object[] bindingParams = new Object[2]; // <Snippet30> IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(bindingParams); factory.Open(); EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp"); IRequestChannel channel = factory.CreateChannel(address); channel.Open(); // </Snippet30> Message request = Message.CreateMessage(MessageVersion.Default, "hello"); Message reply = channel.Request(request); Console.Out.WriteLine(reply.Headers.Action); reply.Close(); channel.Close(); factory.Close(); // </Snippet3> }
void RunTest() { listener.Open(); Thread thread = new Thread(ServerThread); thread.Start(this); CustomBinding binding = new CustomBinding(new WseTcpTransportBindingElement()); IChannelFactory <IDuplexSessionChannel> channelFactory = binding.BuildChannelFactory <IDuplexSessionChannel>(); channelFactory.Open(); IDuplexSessionChannel channel = channelFactory.CreateChannel(new EndpointAddress(this.uri)); Message requestMessage; channel.Open(); requestMessage = Message.CreateMessage(binding.MessageVersion, "http://SayHello", "to you."); channel.Send(requestMessage); Message hello = channel.Receive(); using (hello) { Console.WriteLine(hello.GetBody <string>()); } Console.WriteLine("Press enter."); Console.ReadLine(); requestMessage = Message.CreateMessage(binding.MessageVersion, "http://NotHello", "to me."); channel.Send(requestMessage); channel.Close(); thread.Join(); channelFactory.Close(); listener.Close(); Console.WriteLine("Press enter."); Console.ReadLine(); }
//入口方法 static void Main(string[] args) { try { //建立自定义的通道栈 BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body")) { //创建ChannelFactory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); //这里创建IRequestChannel IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost/RequestReplyService")); requestChannel.Open(); //发送消息 Message response = requestChannel.Request(message); Console.WriteLine("已经成功发送消息!"); //查看返回消息 Console.WriteLine("接受到一条返回消息,action为:{0},body为:{1}", response.Headers.Action, response.GetBody <String>()); requestChannel.Close(); factory.Close(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
public void MessageSecurityManualProtection() { SymmetricSecurityBindingElement sbe = new SymmetricSecurityBindingElement(); sbe.ProtectionTokenParameters = new X509SecurityTokenParameters(); RequestSender sender = delegate(Message input) { MessageBuffer buf = input.CreateBufferedCopy(0x10000); using (XmlWriter w = XmlWriter.Create(Console.Error)) { buf.CreateMessage().WriteMessage(w); } return(buf.CreateMessage()); }; CustomBinding binding = new CustomBinding( sbe, new TextMessageEncodingBindingElement(), new HandlerTransportBindingElement(sender)); EndpointAddress address = new EndpointAddress( new Uri("http://localhost:8080"), new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono"))); ChannelProtectionRequirements reqs = new ChannelProtectionRequirements(); reqs.OutgoingSignatureParts.AddParts( new MessagePartSpecification(new XmlQualifiedName("SampleValue", "urn:foo")), "urn:myaction"); BindingParameterCollection parameters = new BindingParameterCollection(); parameters.Add(reqs); /* * SymmetricSecurityBindingElement innersbe = * new SymmetricSecurityBindingElement (); * innersbe.ProtectionTokenParameters = * new X509SecurityTokenParameters (); * sbe.ProtectionTokenParameters = * new SecureConversationSecurityTokenParameters ( * innersbe, false, reqs); */ IChannelFactory <IRequestChannel> cf = binding.BuildChannelFactory <IRequestChannel> (parameters); cf.Open(); IRequestChannel ch = cf.CreateChannel(address); ch.Open(); try { ch.Request(Message.CreateMessage(MessageVersion.None, "urn:myaction", new SampleValue())); } finally { ch.Close(); } }
public void OpenChannelFactory() { CustomBinding b = CreateBinding(); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.Open(); }
public void BuildChannelWithoutOpen() { CustomBinding b = CreateBinding(); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.CreateChannel(CreateX509EndpointAddress("stream:dummy")); }
public void BuildChannelWithoutProtectionTokenParameters() { CustomBinding b = new CustomBinding( new SymmetricSecurityBindingElement(), new TextMessageEncodingBindingElement(), new HttpTransportBindingElement()); b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); }
public static void IRequestChannel_Http_CustomBinding() { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); // Create the channel factory for the request-reply message exchange pattern. IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); factory.Open(); // Create the channel. IRequestChannel channel = factory.CreateChannel( new EndpointAddress(BaseAddress.HttpBaseAddress)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. Message replyMessage = channel.Request(requestMessage); string replyMessageAction = replyMessage.Headers.Action; if (!string.Equals(replyMessageAction, action + "Response")) { Assert.True(false, String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction)); } var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { Assert.True(false, String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString())); } }
//[WcfFact] //[OuterLoop] public static void IRequestChannel_Async_Http_CustomBinding() { IChannelFactory <IRequestChannel> factory = null; IRequestChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); // Create the channel factory for the request-reply message exchange pattern. factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); Task.Factory.FromAsync(factory.BeginOpen, factory.EndOpen, TaskCreationOptions.None).GetAwaiter().GetResult(); // Create the channel. channel = factory.CreateChannel(new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); Task.Factory.FromAsync(channel.BeginOpen, channel.EndOpen, TaskCreationOptions.None).GetAwaiter().GetResult(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // *** EXECUTE *** \\ // Send the Message and receive the Response. replyMessage = Task.Factory.FromAsync((asyncCallback, o) => channel.BeginRequest(requestMessage, asyncCallback, o), channel.EndRequest, TaskCreationOptions.None).GetAwaiter().GetResult(); // *** VALIDATE *** \\ string replyMessageAction = replyMessage.Headers.Action; Assert.Equal(action + "Response", replyMessageAction); var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); Task.Factory.FromAsync(channel.BeginClose, channel.EndClose, TaskCreationOptions.None).GetAwaiter().GetResult(); Task.Factory.FromAsync(factory.BeginClose, factory.EndClose, TaskCreationOptions.None).GetAwaiter().GetResult(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
[Category("NotWorking")] // it depends on Kerberos public void OpenRequestWithoutServiceCertificateForNonX509() { CustomBinding b = CreateBinding(new MyOwnSecurityTokenParameters()); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.Open(); // This EndpointAddress does not contain X509 identity IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy")); ch.Open(); }
public void SendRequestWithoutOpen() { CustomBinding b = CreateBinding(); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.Open(); IRequestChannel ch = f.CreateChannel(CreateX509EndpointAddress("stream:dummy")); try { ch.Request(Message.CreateMessage(MessageVersion.Default, "myAction")); Assert.Fail("expected InvalidOperationException here."); } catch (InvalidOperationException) { } }
public void OpenRequestWithoutServiceCertificate() { CustomBinding b = CreateBinding(); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection()); f.Open(); // This EndpointAddress does not contain X509 identity IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy")); try { ch.Open(); Assert.Fail("expected InvalidOperationException here."); } catch (InvalidOperationException) { } }
public static void Main() { Console.WriteLine("Press ENTER when service is ready."); Console.ReadLine(); CustomBinding binding = new CustomBinding(); binding.Elements.Add(new TextMessageEncodingBindingElement()); binding.Elements.Add(new TcpTransportBindingElement()); BindingParameterCollection bpcol = new BindingParameterCollection(); // using (IChannelFactory<IDuplexSessionChannel> factory = // binding.BuildChannelFactory<IDuplexSessionChannel>(bpcol)) // { IChannelFactory <IDuplexSessionChannel> factory = binding.BuildChannelFactory <IDuplexSessionChannel> (bpcol); factory.Open(); IDuplexSessionChannel channel = factory.CreateChannel( new EndpointAddress("net.tcp://localhost/")); channel.Open(); Message message = Message.CreateMessage( //channel.Manager.MessageVersion, MessageVersion.Default, "Action", "Hello, World, from client side"); channel.Send(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.Close(); channel.Close(); factory.Close(); // } }
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")); }
static void RunClient() { //Step1: Create a binding with just HTTP. BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); //Step2: Use the binding to build the channel factory. IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); //Open the channel factory. factory.Open(); //Step3: Use the channel factory to create a channel. IRequestChannel channel = factory.CreateChannel( new EndpointAddress("http://localhost:8080/channelapp")); channel.Open(); //Step4: Create a message. Message requestmessage = Message.CreateMessage( binding.MessageVersion, "http://contoso.com/someaction", "This is the body data"); //Send message. Message replymessage = channel.Request(requestmessage); Console.WriteLine("Reply message received"); Console.WriteLine("Reply action: {0}", replymessage.Headers.Action); string data = replymessage.GetBody <string>(); Console.WriteLine("Reply content: {0}", data); //Step5: Do not forget to close the message. replymessage.Close(); //Do not forget to close the channel. channel.Close(); //Do not forget to close the factory. factory.Close(); }
TestConsole() { CustomBinding binding = new CustomBinding(); MtomMessageEncodingBindingElement mtomBindingElement = new MtomMessageEncodingBindingElement(); mtomBindingElement.MessageVersion = MessageVersion.Soap11WSAddressingAugust2004; binding.Elements.Add(mtomBindingElement); binding.Elements.Add(new WseTcpTransportBindingElement()); // WSE sample uses a logical endpoint. So we need to set the physical via separately. EndpointAddress address = new EndpointAddress("soap://stockservice.contoso.com/wse/samples/2003/06/TcpSyncStockService"); // INSERT your HOSTNAME here: string hostname = "localhost"; Uri via = new Uri(string.Format("soap.tcp://{0}/StockService", hostname)); StockServicePortTypeClient client = new StockServicePortTypeClient(binding, address); client.Endpoint.Behaviors.Add(new ClientViaBehavior(via)); Console.WriteLine("Calling {0}", client.Endpoint.Address.Uri.AbsoluteUri); StockQuoteRequest quoteRequest = new StockQuoteRequest(); quoteRequest.symbols = new ArrayOfString(); quoteRequest.symbols.Add("FABRIKAM"); quoteRequest.symbols.Add("CONTOSO"); StockQuotes stocks = client.GetStockQuotes(quoteRequest); foreach (StockQuote quote in stocks) { Console.WriteLine(""); Console.WriteLine("Symbol: " + quote.Symbol); Console.WriteLine("\tName: " + quote.Name); Console.WriteLine("\tLast Price: " + quote.Last); } Console.WriteLine("Press enter."); Console.ReadLine(); binding = new CustomBinding(new WseTcpTransportBindingElement()); this.uri = new Uri("wse.tcp://localhost:9000/a/b/"); this.channelFactory = binding.BuildChannelFactory <IDuplexSessionChannel>(); this.listener = binding.BuildChannelListener <IDuplexSessionChannel>(this.uri); }
static void RunClient() { CustomBinding binding = new CustomBinding(); binding.Elements.Add(new TcpTransportBindingElement()); CustomBinding customBinding = new CustomBinding(); BindingParameterCollection bpCollection = new BindingParameterCollection(); // <Snippet9> BindingContext bContext = new BindingContext(customBinding, bpCollection); IChannelFactory <IOutputChannel> factory = binding.BuildChannelFactory <IOutputChannel>(bContext); // </Snippet9> // <Snippet10> IChannelListener <IOutputChannel> listener = binding.BuildChannelListener <IOutputChannel>(bContext); // </Snippet10> }
static void Main(string[] args) { try { //建立自定义的通道栈 BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码 bindingElements[1] = new HttpTransportBindingElement(); //HTTP传输 CustomBinding binding = new CustomBinding(bindingElements); using (Message message = Message.CreateMessage(binding.MessageVersion, "SendMessage", "Message Body")) { //创建ChannelFactory并打开 IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); //创建IRequestChannel并打开 IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost:9090/RequestReplyService")); requestChannel.Open(); Message response = requestChannel.Request(message); //发送消息, 会阻塞线程等待服务端返回消息 Console.WriteLine("成功发送信息"); //查看返回消息 Console.WriteLine("接收到一条返回消息,action为:{0}, body为:{1}", response.Headers.Action, response.GetBody <string>()); requestChannel.Close(); //关闭通道 factory.Close(); //关闭工厂 } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.WriteLine("press any key to exit..."); Console.ReadKey(); } }
static void RunClient() { //Step1: create a binding with just HTTP CustomBinding binding = new CustomBinding(); binding.Elements.Add(new HttpTransportBindingElement()); //Step2: use the binding to build the channel factory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>( new BindingParameterCollection()); //open the channel factory factory.Open(); //Step3: use the channel factory to create a channel IRequestChannel channel = factory.CreateChannel( new EndpointAddress("http://localhost:8080/channelapp")); channel.Open(); //Step4: create a message Message requestmessage = Message.CreateMessage( MessageVersion.Soap12WSAddressing10, "http://contoso.com/someaction", "This is the body data"); //send message Message replymessage = channel.Request(requestmessage); Console.WriteLine("Reply message received"); Console.WriteLine("Reply action: {0}", replymessage.Headers.Action); string data = replymessage.GetBody <string>(); Console.WriteLine("Reply content: {0}", data); //Step5: don't forget to close the message requestmessage.Close(); replymessage.Close(); //don't forget to close the channel channel.Close(); //don't forget to close the factory factory.Close(); }
// Create the channel factory and open the channel for the request-reply message exchange pattern. public static void RequestReplyChannelFactory_Open() { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); // Create the channel factory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel and open it. Success is anything other than an exception. IRequestChannel channel = factory.CreateChannel(new EndpointAddress("http://localhost/WcfProjectNService.svc")); channel.Open(); } catch (Exception ex) { Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString())); } }
public void SendRequestWithSignatureMessagePart() { CustomBinding b = CreateBinding(); ChannelProtectionRequirements cp = new ChannelProtectionRequirements(); cp.IncomingSignatureParts.AddParts(new MessagePartSpecification(true), "myAction"); cp.IncomingEncryptionParts.AddParts(new MessagePartSpecification(true), "myAction"); BindingParameterCollection parameters = new BindingParameterCollection(); parameters.Add(cp); IChannelFactory <IRequestChannel> f = b.BuildChannelFactory <IRequestChannel> (parameters); f.Open(); IRequestChannel ch = f.CreateChannel(CreateX509EndpointAddress("stream:dummy")); ch.Open(); ch.Request(Message.CreateMessage(b.MessageVersion, "myAction")); }