Main Site Documentation

System.Net.Sockets.SocketException using WebRequest


#1

I’ve bot a Cerbuino board with a WiFly modlue. When I try the following code I get a SocketException.

I can use HTTP_Client or sockets directly with no problem but have not been able to get rid of this exception using WebRequest. Any ideas?

            string Url = "http://www.netmftoolbox.com";

		    HttpWebResponse HttpWResponse;		//request object
		    HttpWebRequest HttpWRequest;			//response object


            // Since the IP of the client doesn't matter I am using DHCP
            wifiBoard.EnableDHCP();
            // Connect to the WiFi network
            wifiBoard.JoinNetwork(ssid, channel, authenticationMode, passPhrase);

            bool noIP = true;
            // Wait until the WiFi module has been assigned an IP address
            while (noIP)
            {
                noIP = wifiBoard.LocalIP == "0.0.0.0";
                Thread.Sleep(250);
            }

            Debug.Print("WiFly IP : " + wifiBoard.LocalIP);
            Debug.Print("WiFly MAC : " + wifiBoard.MacAddress);


            HttpWRequest = (HttpWebRequest)WebRequest.Create(Url);
            
            //           req.Method = "PUT";
            HttpWRequest.Method = "GET";
            HttpWRequest.UserAgent = "MyApp";
            HttpWRequest.KeepAlive = false;
            HttpWRequest.Timeout = 1000;

            try
            {
                HttpWResponse = (HttpWebResponse)(((WebRequest)HttpWRequest).GetResponse());
            }
            catch (Exception ex)
            {
                Debug.Print("exception : " + ex.Message);
            }

#2

Using code tags will make your post more readable. This can be done in two ways:[ol]
Click the “101010” icon and paste your code between the

 tags or...
Select the code within your post and click the "101010" icon.[/ol]
(Generated by QuickReply)

#3

It also helps if you tell us where you are getting the socket exception.


#4

Sorry about the formatting.

The exception happens on the line:
HttpWResponse = (HttpWebResponse)(((WebRequest)HttpWRequest).GetResponse());

Here’s the output:
WiFly IP : 192.168.43.66
WiFly MAC : 00:06:66:80:4d:9f
The thread ‘’ (0x4) has exited with code 0 (0x0).
A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
A first chance exception of type ‘System.Net.WebException’ occurred in System.Http.dll
A first chance exception of type ‘System.Net.WebException’ occurred in System.Http.dll


#5

The socket exception should have an error code of the form 10xxx. Lookup the error code and it will give you, and us, a hint as to what is happening.


#6

I’m not seeing the error code. If I expand the exception I see it’s member variables but nothing of the form 10xxx (There’s an HResult code of 4278190080 deep in the structure but that’s it). Is there another way to get the error code?


#7

@ scoleman2272 - We were able to reproduce your issue, however, only using your provided URL. http://www.netmftoolbox.com returned 0 bytes, as it is a redirect and the WebRequest would (as far as I know) not update the forwarding. Using the link pointed to by http://www.netmftoolbox.com (http://netmftoolbox.codeplex.com/), we encountered your issue. The issue with the original link is also present on Spider with WiFiRS21 using the original link. Changing the URL to almost anything but (for example, google.com) a proper response is sent. Code below is the Spider version.

public partial class Program
    {
        HttpWebResponse response;
        HttpWebRequest request;

        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {
            wifi_RS21.Interface.Open();
            NetworkInterfaceExtension.AssignNetworkingStackTo(wifi_RS21.Interface);

            wifi_RS21.Interface.NetworkAddressChanged += new NetworkInterfaceExtension.NetworkAddressChangedEventHandler(Interface_NetworkAddressChanged);

            WiFiNetworkInfo[] infos = wifi_RS21.Interface.Scan();
            foreach (WiFiNetworkInfo info in infos)
            {
                if (info.SSID == "linksys")
                {
                    Debug.Print("Found linksys with " + info.RSSI.ToString() + "% signal strength.");
                    wifi_RS21.Interface.NetworkInterface.EnableDhcp();
                    wifi_RS21.Interface.Join(info, "no");

                    break;
                }
            }
        }

        void Interface_NetworkAddressChanged(object sender, EventArgs e)
        {
            if (wifi_RS21.Interface.NetworkInterface.IPAddress == "0.0.0.0")
            {
                Debug.Print("Awaiting IP Address");
            }

            else
            {
                Debug.Print("IP Address: " + wifi_RS21.Interface.NetworkInterface.IPAddress);

                Debug.Print("Generating Request");
                request = (HttpWebRequest)HttpWebRequest.Create("http://google.com");
                request.Method = "GET";
                request.UserAgent = "MyApp NETMF";
                request.KeepAlive = false;
                request.Timeout = 1000;

                Debug.Print("Awaiting response...");
                response = (HttpWebResponse)request.GetResponse();
                Debug.Print("Done.\n" + response.ContentLength.ToString() + " bytes");
            }
        }
    }

With the following output

RS9110 firmware version Number is 4.4.5
RS9110 driver version Number is 4.4.5
Found linksys with 68% signal strength.
IP Address: 192.168.1.129
Generating Request
Awaiting response...
Done.
219 bytes

#8

I tried this code as close to verbatum as I could and I still get the exception
In this case:
An unhandled exception of type ‘System.Net.WebException’ occurred in System.Http.dll

In fact I get this exception no matter what I point to

The big difference is that you were using the RS21 wifi and I’m using WiFly. I’m not thinking it’s got something to do with the lower level Wifly drivers.


#9

@ scoleman2272 - We will re-test this with a Cerberus and WiFly, however it could also be how HttpWebRequest fullfills the request. If the request tries to send out more than one request (or the server responds to more than one request) before the WiFly closes the TCP connection, there could be a collision due to the fact that the WiFly module can only have a single active connection. However, we should have more information when we re-test.


#10

@ scoleman2272 - To assist us, would you test using a simple socket using the WiFly module, and report a snippet of working code of this case?


#11

@ scoleman2272, how big is the page you are trying to get? Is it possible you are exceeding the memory limit? You might try using a really small page and see what happens.


#12

The following works fine

            // Creates a socket
            SimpleSocket Socket = new WiFlySocket("www.netduino.com", 80, wifiBoard);

            // Connects to the socket
            Socket.Connect();

            // Does a plain HTTP request
            Socket.Send("GET / HTTP/1.1\r\n");
            Socket.Send("Host: " + Socket.Hostname + "\r\n");
            Socket.Send("Connection: Close\r\n");
            Socket.Send("\r\n");

            // Prints all received data to the debug window, until the connection is terminated and there's no data left anymore
            while (Socket.IsConnected || Socket.BytesAvailable > 0)
            {
                string Text = Socket.Receive();
                if (Text != "")
                    Debug.Print(Text);
            }

            // Closes down the socket
            Socket.Close();

#13

@ scoleman2272 - Okay, I think I see the issue. When you use a simple socket, in this manor, you are actually constructing the socket from the NETMF ToolBox driver for the RN-17x module. This is a single connection module that houses it’s own TCP/IP stack, and you will need to create code to allow the firmware to interface with the TCP/IP stack, if that is even possible with the RN-17x.

The WiFlySocket class most likely inherits from the SimpleSocket class, allowing the SimpleSocket class to function as provided by your last example.


#14

I also get this problem.

I read all replies but still don;t understand how to solve it.

My code is

_wifi.DebugMode = true;
            
            Debug.Print("Initializing WiFi");
            
            _wifi.EnableDHCP();
            _wifi.JoinNetwork("Z1234",0, WiFlyGSX.AuthMode.WPA2_PSK, "569326");

            bool noIP = true;
            while (noIP)
            {
                noIP = _wifi.LocalIP == "0.0.0.0";
                System.Threading.Thread.Sleep(250);
            }

            Debug.Print("WiFly IP  :" + _wifi.LocalIP);
            Debug.Print("WiFly MAC :" + _wifi.MacAddress);
            
            HttpRequest request;
            request = Gadgeteer.Networking.WebClient.GetFromWeb("http://www.netmftoolbox.com");
            request.ResponseReceived += new HttpRequest.ResponseHandler(request_ResponseReceived);

 void request_ResponseReceived(HttpRequest sender, HttpResponse response)
        {
            string text = response.Text;
            Debug.Print("***Response is received : " + text);
        }


Debug.output

WiFly IP :10.59.1.23
WiFly MAC :00:06:66:80:3a:83
A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
A first chance exception of type ‘System.Net.WebException’ occurred in System.Http.dll
The thread ‘’ (0x5) has exited with code 0 (0x0).
A first chance exception of type ‘System.Net.WebException’ occurred in System.Http.dll

An exception occured while connecting to the Internet. Please, make sure that a valid URL is used and a network connection is up.


#15

Just to make sure. Do you have latest firmware installed?


#16

YES
All is latest and my device are Cerbuino Bee and RN-XV-WiFly Module.