Panda II Http Client

Hello,

I am using the sample Http Client code (http://www.tinyclr.com/codeshare/entry/227). By 90% of times I got exeption, when trying to request.GetResponse().

When I once run test project, it worked fine. Then I only re-run the project and got exeption. It is now only reading text file on my domain. I have hilighted the text from the textfile on debug window in Visual Studio, other screen is with exception.

Do you have any ideas what is causing the exeption? Should it be my router or something like that?

I have latest firmware and SDK.

thanks.

try this one instead…
http://www.tinyclr.com/codeshare/entry/363

a lot of great work went into it…

cheers.

Definitely use the one in Jay Jay’s link. I’ve had it running on a project (http://www.ransomhall.com/Pages/MoodCube.aspx) I’ve demoed several times to various groups. Always runs like a champ.

Thanks for the tip. But I need client, not server. I want to send data to my database (using HTTP POST or GET) - just like example for ThingSpeak. That web server should be workaround, but I would need something periodically tasking the board from outside.

Hi there Vit,

can you show us more of your code, more of the debug window output, and explicitly where in the code the exception is thrown? Can you identify where in the overall http get process you think the issue has come from? Can you also emulate the GET from a PC so we can see what the expected response will look like, so that we can understand how that would be handled by your code.

In that case try this:


request.KeepAlive = false;

Ans be sure to read this…
http://www.tinyclr.com/forum/topic?id=3793

Good luck.

This is my code:

using System;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.Net;
using GHIElectronics.NETMF.Net.NetworkInformation;

/// This program demonstrates how to use the .NET Micro Framework HTTP classes 
/// to create a simple HTTP client that retrieves pages from several different 
/// websites, including secure sites.
namespace HttpClientSample {
    public static class MyHttpClient {
        /// <summary>
        /// Retrieves a page from a Web server, using a simple GET request.
        /// </summary>
        public static void Main() {
            
            WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10, (Cpu.Pin)FEZ_Pin.Digital.Di7, true); // WIZnet interface on FEZ Connect

            byte[] IP = { 192, 168, 1, 200 };
            byte[] Subnet = { 255, 255, 255, 0 };
            byte[] Gateway = { 192, 168, 1, 1 };
            byte[] MAC = { 0x00, 0x26, 0x1C, 0x7B, 0x29, 0xE8 };

            Dhcp.EnableDhcp(MAC, "FEZ");

            NetworkInterface.EnableStaticDns(Gateway);
            NetworkInterface.EnableStaticIP(IP, Subnet, Gateway, MAC);
            

            Debug.Print("Network settings:");

            Debug.Print("IP Address: " + new IPAddress(NetworkInterface.IPAddress).ToString());
            Debug.Print("Subnet Mask: " + new IPAddress(NetworkInterface.SubnetMask).ToString());
            Debug.Print("Default Getway: " + new IPAddress(NetworkInterface.GatewayAddress).ToString());
            Debug.Print("DNS Server: " + new IPAddress(NetworkInterface.DnsServer).ToString());
            
            // Print the HTTP data from each of the following pages.
            PrintHttpData("http://meteo.dajbych.net/test.txt");

            // from http://www.tinyclr.com/forum/topic?id=3793&page=1
            Thread.Sleep(Timeout.Infinite);
        }

        /// <summary>
        /// Prints the HTTP Web page from the given URL and status data while 
        /// receiving the page.
        /// </summary>
        /// <param name="url">The URL of the page to print.</param>
        public static void PrintHttpData(string url) {
            // Create an HTTP Web request.
            HttpWebRequest request =
                HttpWebRequest.Create(url) as HttpWebRequest;

            // Set request.KeepAlive to use a persistent connection. 
            request.KeepAlive = false;

            // Get a response from the server.
            WebResponse resp = null;

            try {
                resp = request.GetResponse();
            } catch (Exception e) {
                Debug.Print("Exception in HttpWebRequest.GetResponse(): " + e.ToString());
            }

            // Get the network response stream to read the page data.
            if (resp != null) {
                Stream respStream = resp.GetResponseStream();
                string page = null;
                byte[] byteData = new byte[2048];
                char[] charData = new char[2048];
                int bytesRead = 0;
                Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder();
                int totalBytes = 0;

                // allow 5 seconds for reading the stream
                respStream.ReadTimeout = 5000;

                // If we know the content length, read exactly that amount of 
                // data; otherwise, read until there is nothing left to read.
                if (resp.ContentLength != -1) {
                    for (int dataRem = (int)resp.ContentLength; dataRem > 0; ) {
                        Thread.Sleep(500);
                        bytesRead =
                            respStream.Read(byteData, 0, byteData.Length);
                        if (bytesRead == 0) {
                            Debug.Print("Error: Received " +
                                (resp.ContentLength - dataRem) + " Out of " +
                                resp.ContentLength);
                            break;
                        }
                        dataRem -= bytesRead;

                        // Convert from bytes to chars, and add to the page 
                        // string.
                        int byteUsed, charUsed;
                        bool completed = false;
                        totalBytes += bytesRead;
                        UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0,
                            bytesRead, true, out byteUsed, out charUsed,
                            out completed);
                        page = new String(charData, 0, charUsed);
                        // Display the page results.
                        Debug.Print(page);

                    }

                    page = new String(
                        System.Text.Encoding.UTF8.GetChars(byteData));
                } else {
                    // Read until the end of the data is reached.
                    while (true) {
                        // If the Read method times out, it throws an exception, 
                        // which is expected for Keep-Alive streams because the 
                        // connection isn't terminated.
                        try {
                            Thread.Sleep(500);
                            bytesRead =
                                respStream.Read(byteData, 0, byteData.Length);
                        } catch (Exception) {
                            bytesRead = 0;
                        }

                        // Zero bytes indicates the connection has been closed 
                        // by the server.
                        if (bytesRead == 0) {
                            break;
                        }

                        int byteUsed, charUsed;
                        bool completed = false;
                        totalBytes += bytesRead;

                        UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0,
                            bytesRead, true, out byteUsed, out charUsed,
                            out completed);
                        page = new String(charData, 0, charUsed);

                        // Display the page results.
                        Debug.Print(page);

                    }
                }

                // Close the response stream.  For Keep-Alive streams, the 
                // stream will remain open and will be pushed into the unused 
                // stream list.
                resp.Close();
            }
        }
    }
}

and when I run it first time today, it worked well, but not second time.

Little progress.

I have downloaded W5100.Http source code from CodePlex and found problem line. As I mantioned before, sometimes code works, sometimes not.

problem is (I hope) here:

hostEntry = Dns.GetHostEntry(proxyServer.Host);

It returns null value. When not, Http request works. This seems to be problem in W5100.Dns library.

Any ideas how to solve this?

In this scenario, what i would do is try to use netmon to capture the traffic. It seems to me that your router isn’t responding with the DNS looked-up address so it makes sense that it fails, because it doesn’t know where to go. It also explains why it works sometimes and other times not; because some times your router responds and other times not.

One possible workaround is to explicitly set a DNS address that is not your router (which will eliminate it as your possible failure point). If the reason that your router doesn’t respond (or doesn’t respond in what ever timeout the Fez operates in, which I don’t know) is because it is taking time getting the answer from an upstream DNS server, then pointing to the upstream DNS server is unlikely to help, but it might be a good test none the less.

Thank you Brett,

setting public DNS server helped me. This is now my network initialization:

byte[] IP = { 192, 168, 1, 200 };
byte[] Subnet = { 255, 255, 255, 0 };
byte[] Gateway = { 192, 168, 1, 1 };
byte[] Dns = { 8, 8, 8, 8 }; // Google DNS server
byte[] MAC = { 0x00, 0x26, 0x1C, 0x7B, 0x29, 0xE8 };

Dhcp.EnableDhcp(MAC, "FEZ");

NetworkInterface.EnableStaticDns(Dns);
NetworkInterface.EnableStaticIP(IP, Subnet, Gateway, MAC);

and works great now.