Microsoft  CSIP   WindowsMobile   MEDC   合作伙伴   体验中心 设为首页 加到收藏夹

 
登录       点击换一张     注册新用户 找回密码

Windows Mobile上的GPRS连接(基于TcpClient)
2008年08月18日10:15   编辑:黄季冬编译 来源: 博客 浏览: 241

         在有线的连接和WIFI都不可用的时候, .NET CF的HttpWebRequest会由于web requests/web services 而自动设置GPRS连接。所以实际上当你发起一个Web请求或者连接Webservice的时候,并不需要开发者编码处理GPRS的连接问题。不过对于更低层的通信,如使用TcpClient 和 UdpClient的时候,则需要为咩使用 Connection Manager API来建立和释放连接。

        (本文英文原文见:http://blogs.msdn.com/anthonywong/archive/2006/03/13/550686.aspx)

        以下托管类是对Connection Manager API的封装

   public class GPRSConnection
    
{
        
const int S_OK = 0;
        
const uint CONNMGR_PARAM_GUIDDESTNET = 0x1;
        
const uint CONNMGR_FLAG_PROXY_HTTP = 0x1;
        
const uint CONNMGR_PRIORITY_USERINTERACTIVE = 0x08000;
        
const uint INFINITE = 0xffffffff;
        
const uint CONNMGR_STATUS_CONNECTED = 0x10;
        
static Hashtable ht = new Hashtable();

        
static GPRSConnection()
        
{
            ManualResetEvent mre 
= new ManualResetEvent(false);
            mre.Handle 
= ConnMgrApiReadyEvent();
            mre.WaitOne();
            CloseHandle(mre.Handle);
        }


        
~GPRSConnection()
        
{
            ReleaseAll();
        }


        
public static bool Setup(Uri url)
        
{
            
return Setup(url.ToString());
        }


        
public static bool Setup(string urlStr)
        
{
            ConnectionInfo ci 
= new ConnectionInfo();
            IntPtr phConnection 
= IntPtr.Zero;
            
uint status = 0;

            
if (ht[urlStr] != null)
                
return true;

            
if (ConnMgrMapURL(urlStr, ref ci.guidDestNet, IntPtr.Zero) != S_OK)
                
return false;
            
            ci.cbSize 
= (uint) Marshal.SizeOf(ci);
            ci.dwParams 
= CONNMGR_PARAM_GUIDDESTNET;
            ci.dwFlags 
= CONNMGR_FLAG_PROXY_HTTP;
            ci.dwPriority 
= CONNMGR_PRIORITY_USERINTERACTIVE;
            ci.bExclusive 
= 0;
            ci.bDisabled 
= 0;
            ci.hWnd 
= IntPtr.Zero;
            ci.uMsg 
= 0;
            ci.lParam 
= 0;

            
if (ConnMgrEstablishConnectionSync(ref ci, ref phConnection, INFINITE, ref status) != S_OK &&
                status 
!= CONNMGR_STATUS_CONNECTED)
                
return false;

            ht[urlStr] 
= phConnection;
            
return true;
        }


        
public static bool Release(Uri url)
        
{
            
return Release(url.ToString());
        }


        
public static bool Release(string urlStr)
        
{
            
return Release(urlStr, true);
        }