在Windows Mobile中管理网络状态的最佳方法 [英] Best way to manage network state in Windows Mobile

查看:63
本文介绍了在Windows Mobile中管理网络状态的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET Compact Framework 3.5程序,该程序用作偶尔连接的业务(LOB)应用程序。如果可以看到在线Web服务,它将使用该Web服务进行数据访问,但是如果网络连接丢失,它将使用本地缓存。

I have a .NET Compact Framework 3.5 program that is used as a 'Occasionally Connected' line of business (LOB) application. If it can see an online webservice, it will use that for data access, but if network connection is lost it will use a local cache.

处理所有连接选项和状态更改的最佳方法是什么?

What is the best way to handle all of the connection options and state changes?


  • OpenNetCF的ConnectionManager类?

  • Microsoft.WindowsBile.State.SystemState?

  • API调用?

如何了解WiFi,Cradle和GPRS之间的区别并使用最佳方法?

How do you get it to understand the difference between WiFi, Cradle, and GPRS and use the best method available?

有人对此有任何指导吗?

Anyone have any guidance on this?

推荐答案

我只是创建我可以这样调用一个简单的共享类:

I just create a simple shared class that I can call like this:

If MyConnectionClass.IsConnected then
     'Do connected stuff
Else
     'Do local save
End If

然后全部实际的业务类/功能可以使用它来从UI代码中隐藏这种麻烦。

Then all of my actual business classes/functions can use this to hide this nastiness from the UI code.

MyConnectionClass的IsConnected属性将具有以下内容:

The MyConnectionClass' IsConnected property would have something like this:

Public ReadOnly Property IsConnected As Boolean
   Get
    Try

        Dim HostName As String = Dns.GetHostName()
        Dim thisHost As IPHostEntry = Dns.GetHostByName(HostName)
        Dim thisIpAddr As String = thisHost.AddressList(0).ToString

        return (thisIpAddr <> Net.IPAddress.Parse("127.0.0.1").ToString())

    Catch ex As Exception
        Return False
    End Try
   End Get
End Property

还建议您轮询使用后台线程获取连接状态,然后在状态更改时将事件触发回主应用线程。这是详细的文章:

It is also recommended that you poll for connection status using a background thread and then fire an event back to the main app thread when the state changes. Here is the detailed writeup:

在.NET Compact Framework中测试和响应网络连接

编辑:

现在,要获得 GPRS 支持:

如果您使用的是Web请求或Web服务,则框架将为您处理连接。如果您要深入研究TCPClient或UDPClient,则需要使用连接管理器API自己来处理它:

If you are using Web Requests or Web Services, the framework will handle the connection for you. If you are diving deeper into TCPClient or UDPClient, you need to handle it with the Connection manager API's yourself like so:

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);
    }

    private static bool Release(string urlStr, bool removeNode)
    {
        bool res = true;
        IntPtr ph = IntPtr.Zero;
        if (ht[urlStr] == null)
            return true;
        ph = (IntPtr)ht[urlStr];
        if (ConnMgrReleaseConnection(ph, 1) != S_OK)
            res = false;
        CloseHandle(ph);
        if (removeNode)
            ht.Remove(urlStr);
        return res;
    }

    public static void ReleaseAll()
    {
       foreach(DictionaryEntry de in ht)
       {
           Release((string)de.Key, false);
       }
       ht.Clear();
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct ConnectionInfo
    {
        public uint cbSize;
        public uint dwParams;
        public uint dwFlags;
        public uint dwPriority;
        public int bExclusive;
        public int bDisabled;
        public Guid guidDestNet;
        public IntPtr hWnd;
        public uint uMsg;
        public uint lParam;
        public uint ulMaxCost;
        public uint ulMinRcvBw;
        public uint ulMaxConnLatency;
    }

    [DllImport("cellcore.dll")]
    private static extern int ConnMgrMapURL(string pwszURL, ref Guid pguid, IntPtr pdwIndex);

    [DllImport("cellcore.dll")]
    private static extern int ConnMgrEstablishConnectionSync(ref ConnectionInfo ci, ref IntPtr phConnection, uint dwTimeout, ref uint pdwStatus);

    [DllImport("cellcore.dll")]
    private static extern IntPtr ConnMgrApiReadyEvent();

    [DllImport("cellcore.dll")]
    private static extern int ConnMgrReleaseConnection(IntPtr hConnection, int bCache);

    [DllImport("coredll.dll")]
    private static extern int CloseHandle(IntPtr hObject);
}

要使用它,请执行以下操作:

And to use it, do this:

public void DoTcpConnection()
    {
        string url = "www.msn.com";
        bool res = GPRSConnection.Setup("http://" + url + "/");
        if (res)
        {
            TcpClient tc = new TcpClient(url, 80);
            NetworkStream ns = tc.GetStream();
            byte[] buf = new byte[100];
            ns.Write(buf, 0, 100);
            tc.Client.Shutdown(SocketShutdown.Both);
            ns.Close();
            tc.Close();
            MessageBox.Show("Wrote 100 bytes");
        }
        else
        {
            MessageBox.Show("Connection establishment failed");
        }
    }

这是来自Anthony Wong的博客:

This was from Anthony Wong's blog here:

Anthony Wong

请记住,只有较低级别的TCP或UDP内容才需要此功能。 HTTPRequests不需要这个。

And remember you only need this for lower level TCP or UDP stuff. HTTPRequests don't need this.

这篇关于在Windows Mobile中管理网络状态的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆