public void Open() { HttpBinding binding = new HttpBinding(); this.ChannelListener = binding.BuildChannelListener<IReplyChannel>(this.BaseAddress); this.ChannelListener.Open(); IReplyChannel channnel = this.ChannelListener.AcceptChannel(); channnel.Open(); while (true) { RequestContext requestContext = channnel.ReceiveRequest(TimeSpan.MaxValue); Message message = requestContext.RequestMessage; MethodInfo method = message.GetType().GetMethod("GetHttpRequestMessage"); HttpRequestMessage request = (HttpRequestMessage)method.Invoke(message, new object[] { true }); Task<HttpResponseMessage> processResponse = base.SendAsync(request, new CancellationTokenSource().Token); processResponse.ContinueWith(task => { string httpMessageTypeName = "System.Web.Http.SelfHost.Channels.HttpMessage, System.Web.Http.SelfHost"; Type httpMessageType = Type.GetType(httpMessageTypeName); Message reply = (Message)Activator.CreateInstance(httpMessageType, new object[] { task.Result }); requestContext.Reply(reply); }); } }
static void Main(string[] args) { Uri listenUri = new Uri("http://127.0.0.1:3721"); Binding binding = new HttpBinding(); //创建、开启信道监听器 IChannelListener<IReplyChannel> channelListener = binding.BuildChannelListener<IReplyChannel>(listenUri); //调用BuildChannelListener<IReplyChannel>方法创建一个channelListener管道 channelListener.Open(); //创建、开启回复信道 IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue); channel.Open(); //开始监听 while (true) { //接收输出请求消息 RequestContext requestContext = channel.ReceiveRequest(TimeSpan.MaxValue); PrintRequestMessage(requestContext.RequestMessage); //消息回复 requestContext.Reply(CreateResponseMessage()); } }
private void BeginOpenListener(HttpSelfHostServer server) { Contract.Assert(server != null); try { // Create WCF HTTP transport channel HttpBinding binding = new HttpBinding(); // Get it configured BindingParameterCollection bindingParameters = server._configuration.ConfigureBinding(binding); if (bindingParameters == null) { bindingParameters = new BindingParameterCollection(); } // Build channel listener server._listener = binding.BuildChannelListener<IReplyChannel>(server._configuration.BaseAddress, bindingParameters); if (server._listener == null) { throw Error.InvalidOperation(SRResources.InvalidChannelListener, typeof(IChannelListener).Name, typeof(IReplyChannel).Name); } IAsyncResult result = server._listener.BeginOpen(_onOpenListenerComplete, server); if (result.CompletedSynchronously) { OpenListenerComplete(result); } } catch (Exception e) { FaultTask(server._openTaskCompletionSource, e); } }