稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTcpBinding的支持, 在Socket通信中通过HTTP检索策略文件, HTTP请求中的ClientHttp和Browse

稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTcpBinding的支持, 在Socket通信中通过HTTP检索策略文件, HTTP请求中的ClientHttp和Browse,第1张

概述  [源码下载] 稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTcpBinding的支持, 在Socket通信中通过HTTP检索策略文件, HTTP请求中的ClientHttp和BrowserHttp 作者: webabcd 介绍 Silverlight 4.0 通信方面的增强: NetTcpBinding - 通过  NetTcpBinding 与 WCF 服务进行通   [源码下载]

稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTcpBinding的支持,在Socket通信中通过http检索策略文件,http请求中的ClIEnthttp和browserhttp
作者: webabcd
介绍
Silverlight 4.0 通信方面的增强:
NetTcpBinding - 通过  NetTcpBinding 与 WCF 服务进行通信 支持在 Socket 通信中通过 http 的方式检索策略文件  http 请求中的 ClIEnthttp 方式和 browserhttp 方式的应用
在线DEMO
http://www.cnblogs.com/webabcd/archive/2010/08/09/1795417.html
示例
1、演示如何通过 NetTcpBinding 与 WCF 进行双向通信
服务端:
IDuplex.cs

代码 /*
 * 双向通信的 Contract
 
*/

using  System;
using  System.Collections.Generic;
using  System.linq;
using  System.Text;

using  System.ServiceModel;

namespace  SocketServer
{
    [ServiceContract(CallbackContract 
=   typeof (IDuplexCallback))]
    
public   interface  IDuplex
    {
        [OperationContract(IsOneWay 
=   true )]
        
voID  HelloDuplex( string  msg);
    }

    
public   interface  IDuplexCallback
    {
        [OperationContract(IsOneWay 
=   true )]
        
voID  HelloDuplexCallback( string  msg);
    }
}

Duplex.cs

代码 /*
 * 实现 IDuplex 契约
 
*/

using  System;
using  System.Collections.Generic;
using  System.linq;
using  System.Text;

using  System.ServiceModel;

namespace  SocketServer
{
    
public   class  Duplex : IDuplex
    {
        
private  IDuplexCallback _callback;

        
//  服务端方法,其用于被客户端调用
         public   voID  HelloDuplex( string  msg)
        {
            Program.Form1.ShowMessage(msg);

            
if  (_callback  ==   null )
            {
                
//  实例化回调接口
                _callback  =  OperationContext.Current.GetCallbackChannel < IDuplexCallback > ();

                
//  每一秒调用一次回调接口(即调用客户端的方法)
                System.Timers.Timer timer  =   new  System.Timers.Timer();
                timer.Interval 
=  3000d;
                timer.Elapsed 
+=   delegate  { _callback.HelloDuplexCallback( " 服务端发给客户端的信息: "   +  DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss " )); };
                timer.Start();
            }
        }
    }
}

App.config

代码 <? xml version="1.0" en@R_301_5563@="utf-8"  ?>
< configuration >
    
< system.serviceModel >
        
< services >
            
<!--
                元数据地址:http://localhost:12345/SocketServer/Duplex/mex
                TCP 地址:net.tcp://localhost:4502/SocketServer/Duplex
                TCP 端口限制在 4502 - 4534 之间
            
-->
            
< service  name ="SocketServer.Duplex" >
                
< endpoint  address ="SocketServer/Duplex"  binding ="customBinding"  contract ="SocketServer.IDuplex"   />
                
< endpoint  address ="mex"  binding ="mexhttpBinding"  contract ="IMetadataExchange"   />
                
< host >
                    
< baseAddresses >
                        
< add  baseAddress ="http://localhost:12345/SocketServer/Duplex"   />
                        
< add  baseAddress ="net.tcp://localhost:4502/"   />
                    
</ baseAddresses >
                
</ host >
            
</ service >
        
</ services >
        
        
<!--
            Silverlight 4.0 对 NetTcpBinding 的支持是通过自定义绑定的方式来实现的。服务端和客户端都需要使用自定义绑定
        
-->
        
< bindings >
            
< customBinding >
                
< binding >
                    
< binaryMessageEn@R_301_5563@ ></ binaryMessageEn@R_301_5563@ >
                    
< tcpTransport  maxReceivedMessageSize ="2147483647"  maxBufferSize ="2147483647"   />
                
</ binding >
            
</ customBinding >
        
</ bindings >
        
        
< behaviors >
            
< serviceBehaviors >
                
< behavior >
                    
< serviceMetadata  httpGetEnabled ="true"   />
                    
< serviceDeBUG  includeExceptionDetailinFaults ="true" />
                
</ behavior >
            
</ serviceBehaviors >
        
</ behaviors >
    
</ system.serviceModel >
</ configuration >
Form1.cs

代码 //  启动 WCF 服务,用于演示 Silverlight 4.0 与 WCF 的交互(基于 NetTcpBinding 绑定)
private   voID  LaunchNetTcpBinding()
{
    ServiceHost host 
=   new  ServiceHost( typeof (SocketServer.Duplex));
    host.open();

    ShowMessage(
" 演示 NetTcpBinding 的 WCF 服务已启动 " );
}

客户端(需要引用服务的元数据):
NetTcpBinding.xaml

代码 < navigation:Page  x:Class ="Silverlight40.Communication.NetTcpBinding"  
           xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
           xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"  
           xmlns:d
="http://schemas.microsoft.com/Expression/blend/2008"
           xmlns:mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
           xmlns:navigation
="clr-namespace:System.windows.Controls;assembly=System.windows.Controls.Navigation"
           Title
="NetTcpBinding Page" >
    
< GrID  x:name ="LayoutRoot" >
        
< StackPanel  HorizontalAlignment ="left" >

            
< button  name ="btnSend"  Content ="发送信息到服务端"  Click ="btnSend_Click"   />
            
            
< TextBlock  name ="lblMsg"   />
            
        
</ StackPanel >
    
</ GrID >
</ navigation:Page >

NetTcpBinding.xaml.cs

代码 using  System;
using  System.Collections.Generic;
using  System.linq;
using  System.Net;
using  System.windows;
using  System.windows.Controls;
using  System.windows.documents;
using  System.windows.input;
using  System.windows.Media;
using  System.windows.Media.Animation;
using  System.windows.Shapes;
using  System.windows.Navigation;

using  System.ServiceModel;
using  System.Net.sockets;
using  System.ServiceModel.Channels;

namespace  Silverlight40.Communication
{
    
public   partial   class  NetTcpBinding : Page, DuplexServiceReference.IDuplexCallback
    {
        
private  DuplexServiceReference.DuplexClIEnt _clIEnt;

        
public  NetTcpBinding()
        {
            InitializeComponent();
        }

        
protected   overrIDe   voID  OnNavigatedTo(NavigationEventArgs e)
        {
           
        }


        
private   voID  btnSend_Click( object  sender, RoutedEventArgs e)
        {
            
//  客户端与服务端之间如果没有信道的话,则产生这个信道
             if  (_clIEnt  ==   null )
            {
                var ctx 
=   new  InstanceContext( this );
                
                
//  通过配置文件的方式建立信道
                _clIEnt  =   new  DuplexServiceReference.DuplexClIEnt(ctx);

                
//  通过编写代码的方式建立信道
                 /*
                EndpointAddress ea = new EndpointAddress("net.tcp://localhost:4502/SocketServer/Duplex");
                BindingElement be = new TcpTransportBindingElement();
                CustomBinding cb = new CustomBinding(be);
                _clIEnt = new DuplexServiceReference.DuplexClIEnt(ctx, cb, ea);
                
*/
            }

            
//  调用服务端的方法
            _clIEnt.HelloDuplexAsync( " 客户端发给服务端的信息: "   +  DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss " ));
            
//  _clIEnt.HelloDuplexCompleted - 在此 Handler 中获取服务端方法的返回值,因为本例是 IsOneWay 方式,所以没有返回值
        }

        
//  客户端方法,其用于被服务端调用
         public   voID  HelloDuplexCallback( string  msg)
        {
            lblMsg.Text 
+=  msg  +   " \n " ;
        }
    }
}

ServiceReferences.ClIEntConfig

代码 < configuration >
    
< system.serviceModel >
        
<!--
            使用 NetTcpBinding 绑定需要先引用 System.ServiceModel.NetTcp.dll 程序集
        
-->
        
< clIEnt >
            
< endpoint  address ="net.tcp://localhost:4502/SocketServer/Duplex"  binding ="customBinding"  contract ="DuplexServiceReference.IDuplex"
                      bindingConfiguration
="netTcpBinding"   />
        
</ clIEnt >

        
<!--
            Silverlight 4.0 对 NetTcpBinding 的支持是通过自定义绑定的方式来实现的。服务端和客户端都需要使用自定义绑定
        
-->
        
< bindings >
            
< customBinding >
                
< binding  name ="netTcpBinding" >
                    
< binaryMessageEn@R_301_5563@  />
                    
< tcpTransport  maxReceivedMessageSize ="2147483647"  maxBufferSize ="2147483647"   />
                
</ binding >
            
</ customBinding >
        
</ bindings >
    
</ system.serviceModel >
</ configuration >

2、通过 http 的方式检索 Socket 通信的安全策略
SocketClIEntRetrIEvePolicyfileViahttp.xaml

代码 < navigation:Page  x:Class ="Silverlight40.Communication.socketClIEntRetrIEvePolicyfileViahttp"  
           xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
           xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"  
           xmlns:d
="http://schemas.microsoft.com/Expression/blend/2008"
           xmlns:mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
           xmlns:navigation
="clr-namespace:System.windows.Controls;assembly=System.windows.Controls.Navigation"
           Title
="SocketCommunicationRetrIEvePolicyfileViahttp Page" >
    
< GrID  x:name ="LayoutRoot" >

        
< TextBlock >
            
< Run > 以前的 Socket 通信,在连接之前先要以 943 端口的 TCP 方式在服务端检索策略文件 </ Run >
            
< lineBreak  />
            
< Run > Silverlight 4.0 中的 Socket 通信可以通过 80 端口的 http 方式检索策略文件,获取到的策略文件作用于此 http 地址所解析出的 IP </ Run >
            
< lineBreak  />
            
< Run > System.Net.sockets.socketasynceventargs.socketClIEntAccesspolicyProtocol - 指定 Socket 通信检索策略文件的方式 [System.Net.sockets.socketClIEntAccesspolicyProtocol 枚举] </ Run >
            
< lineBreak  />
            
< Run > 可能的值有:System.Net.sockets.socketClIEntAccesspolicyProtocol.http 和 System.Net.sockets.socketClIEntAccesspolicyProtocol.Tcp </ Run >
        
</ TextBlock >
        
    
</ GrID >
</ navigation:Page >

3、两种 http 请求方式,即 ClIEnthttp 和 browserhttp 的区别
httpResult.aspx.cs

代码 using  System;
using  System.Collections.Generic;
using  System.linq;
using  System.Web;
using  System.Web.UI;
using  System.Web.UI.WebControls;

namespace  Silverlight40.Web
{
    
public   partial   class  httpResult : System.Web.UI.Page
    {
        
protected   voID  Page_Load( object  sender, EventArgs e)
        {
            
//  返回当前 http 请求的 http 方法及 cookie
            Response.Write( string .Format( " httpMethod: {0}, cookie - name: {1} " , Request.httpMethod, Request.cookies[ " name " ].Value));
            Response.End();
        }
    }
}

客户端:
ClIEnthttpAndbrowserhttp.xaml.cs

代码 /*
 * browserhttp - 由浏览器构造 http 请求。默认值
 * ClIEnthttp - 由 Silverlight 客户端构造 http 请求
 * 
 * 指定 http 请求为 browserhttp 类型或 ClIEnthttp 类型的方法如下:
 *     WebRequest.RegisterPrefix("http://", WebRequestCreator.ClIEnthttp); - 根据前缀指定 http 请求的方式
 *     (httpWebRequest)WebRequestCreator.ClIEnthttp.Create(); - 为单个请求指定 http 请求的方式
 * 
 * 本例演示如果通过 ClIEnthttp,来实现 PUT 方法的 http 请求以及如何手动构造 cookie(这些在 browserhttp 方式下是无法实现的)
 * 详细的 browserhttp 和 ClIEnthttp 的区别参看文档
 
*/

using  System;
using  System.Collections.Generic;
using  System.linq;
using  System.Net;
using  System.windows;
using  System.windows.Controls;
using  System.windows.documents;
using  System.windows.input;
using  System.windows.Media;
using  System.windows.Media.Animation;
using  System.windows.Shapes;
using  System.windows.Navigation;

using  System.Net.browser;
using  System.IO;
using  System.Threading;

namespace  Silverlight40.Communication
{
    
public   partial   class  ClIEnthttpAndbrowserhttp : Page
    {
        SynchronizationContext _syncContext;

        
public  ClIEnthttpAndbrowserhttp()
        {
            InitializeComponent();
        }

        
protected   overrIDe   voID  OnNavigatedTo(NavigationEventArgs e)
        {
            _syncContext 
=  SynchronizationContext.Current;

            
//  创建一个 ClIEnthttp 方式的 httpWebRequest 对象
            httpWebRequest request  =  (httpWebRequest)WebRequestCreator.ClIEnthttp.Create( new  Uri( " http://localhost:9483/httpResult.aspx " ));

            
//  ClIEnthttp 可以使用任何 http 方法(browserhttp 只能使用 GET 和 POST)
            request.Method  =   " PUT " ;

            
//  ClIEnthttp 可以手工构造 cookie(如果需要 Forms 验证或 NTLM 验证则只能通过 broswerhttp 方式)
            request.cookieContainer  =   new  cookieContainer();
            request.cookieContainer.Add(
new  Uri( " http://localhost:9483 " ),  new  cookie( " name " " webabcd " ));

            request.BeginGetResponse(
new  AsyncCallback(ResponseCallback), request);

        }

        
//  获取服务返回的结果
         private   voID  ResponseCallback(IAsyncResult result)
        {
            httpWebRequest request 
=  result.AsyncState  as  httpWebRequest;
            WebResponse response 
=  request.EndGetResponse(result)  as  httpWebResponse;

            
if  (response  !=   null )
            {
                Stream responseStream 
=  response.GetResponseStream();
                
using  (StreamReader sr  =   new  StreamReader(responseStream))
                {
                    
string  s  =  sr.ReadToEnd();
                    Deployment.Current.dispatcher.BeginInvoke(
delegate  { MessageBox.Show(s); });
                }
            }
        }
    }
}

OK
[源码下载] 总结

以上是内存溢出为你收集整理的稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTcpBinding的支持, 在Socket通信中通过HTTP检索策略文件, HTTP请求中的ClientHttp和Browse全部内容,希望文章能够帮你解决稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTcpBinding的支持, 在Socket通信中通过HTTP检索策略文件, HTTP请求中的ClientHttp和Browse所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1071659.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存