Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Web server up and running - not all html text showing

web server

  • Please log in to reply
19 replies to this topic

#1 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 14 April 2013 - 03:20 PM

Hi there.

 

I'm very proud that I got a web server up and running  :) However, not all text is showing on the html page and I cant figure out why that is. Its like it hangs while loading the page. Does that make sense?

 

The code I use is copy and paste stuff from other forum members (its the best way for me to learn how it works).

 

The code I have now and which produces a partial html page is below and I attach a screenshot of the html page.

 

All help is appreciated :)

using System;using Microsoft.SPOT;using System.Net.Sockets;using System.Net;using System.Threading;using System.Text;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware.NetduinoPlus;namespace WebserverHelloWorld{    public class WebServer : IDisposable    {        private OutputPort dout_0 = new OutputPort(Pins.GPIO_PIN_D2, false);        private OutputPort dout_1 = new OutputPort(Pins.GPIO_PIN_D3, false);        private OutputPort dout_2 = new OutputPort(Pins.GPIO_PIN_D12, false);        private OutputPort dout_3 = new OutputPort(Pins.GPIO_PIN_D13, false);                private Socket socket = null;           public WebServer()        {            //Initialize Socket class            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            //Request and bind to an IP from DHCP server            socket.Bind(new IPEndPoint(IPAddress.Any, 80));            //Debug print our IP address            Debug.Print(Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);            //Start listen for web requests            socket.Listen(10);            ListenForRequest();        }        public void ListenForRequest()        {            while (true)            {                using (Socket clientSocket = socket.Accept())                {                    //Get clients IP                    IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;                    EndPoint clientEndPoint = clientSocket.RemoteEndPoint;                    //int byteCount = cSocket.Available;                    int bytesReceived = clientSocket.Available;                    if (bytesReceived > 0)                    {                        //Get request                        byte[] buffer = new byte[bytesReceived];                        int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);                        string request = new string(Encoding.UTF8.GetChars(buffer));                        Debug.Print(request);                        //Compose a response                        string response = "Hello World";                        string header = "HTTP/1.0 200 OKrnContent-Type: text; charset=utf-8rnContent-Length: " + response.Length.ToString() + "rnConnection: closernrn";                                                // New test 2013-04-14                        bool vdout_0 = dout_0.Read();                        bool vdout_1 = dout_1.Read();                        bool vdout_2 = dout_2.Read();                        bool vdout_3 = dout_3.Read();                                                //Make some html                        response = "<!DOCTYPE html>";                        response += "<html>";                        response += "<head>";		                        response += "<title>Netduino Plus</title>";                        response += "</head>";                        response += "<body>";                        response += "<h1>Netduino Plus</h1>";                        response += "Out 1 = " + vdout_1.ToString() + "<br/>";                        response += "Out 2 = " + vdout_2.ToString() + "<br/>";                        response += "Out 3 = " + vdout_3.ToString() + "<br/>";                                                response += "</body>";                        response += "</html>";                        // End test 2013-04-14                                                clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);                        clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);                                            }                }            }        }        #region IDisposable Members        ~WebServer()        {            Dispose();        }        public void Dispose()        {            if (socket != null)                socket.Close();        }        #endregion    }}

Attached File  Clipboard01.jpg   60.88KB   28 downloads


Netduino Plus 2 (v4.2.2.2)


#2 martin2250

martin2250

    Advanced Member

  • Members
  • PipPipPip
  • 37 posts
  • LocationGermany

Posted 14 April 2013 - 06:15 PM

my first guess would be that your Socket is getting disposed too quickly, you might want to try adding Thread.Sleep(200) roundabout, right after you write the content to the Socket.

 

also, you could use NetworkStreams, I think they are a little bit better, and more clear.

 

Greetings



#3 baxter

baxter

    Advanced Member

  • Members
  • PipPipPip
  • 415 posts

Posted 14 April 2013 - 07:26 PM

Perhaps your content length in the header is incorrect. It looks like you are setting it too

early (e.g. before // New test 2013-04-14). Also, remember to escape (") in the HTML

with (""). I generally use the following procedure with content to send = ComposeResponse(Message),

'Response and web page    '---------------------    '"<|>" is a placeholder for the content length (see: SetContentLength)    Dim ResponseHeader As String = "HTTP/1.1 200 OK" & vbCrLf & _                                    "Server: Netduino_Mini_WIZ105SR" & vbCrLf & _                                    "Content-Length: " & "<|>" & vbCrLf & _                                    "Connection: close" & vbCrLf & _                                    "Content-Type: text/html" & _                                    vbCrLf & vbCrLf    '<link> tag is to kill the "GET /favicon.ico HTTP/1.1" from IE browser    '<span id = "data"> is to identify the message body for extraction from    'from the Webbrowser control as innertext.    'response = ResponseHeader & html1 & message & html2 (after filling in content length)    Dim Html1 As String = "<!DOCTYPE html>" & _                                "<html>" & _                                    "<head>" & _                                        "<link rel=""shortcut icon"" href=""#""/>" & _                                    "</head>" & _                                    "<body>" & _                                        "<h1 style=""text-align:center;"">" & _                                              "Mini with Ethernet" & _                                        "</h1>" & _                                        "<p style=""font-family:arial;color:red;font-size:20px;""><span id=""data"">"    Dim Html2 As String = "</span></p>" & "</body>" & "</html>"Public Function ComposeResponse(Message As String) As String        'The total body of response HTML        Dim S0 As String = (Html1 & Message & Html2).Trim        'set the total body length in the response header        Dim S As String = SetContentLength(ResponseHeader, S0) & S0        Return S 'this is to send --> header + web page    End Function    Public Function SetContentLength(ResponseHeader As String, Responsebody As String) As String        'substitute response body length for response header content length place holder, <|>        Dim S As String = replace(ResponseHeader, "<|>", Responsebody.Length.ToString)        Return S    End Function    Public Function replace(ByVal str As String,                            ByVal ToReplace As String,                            ByVal ReplaceWith As String) As String        Dim sb As New System.Text.StringBuilder(1024)        sb.Replace(ToReplace, ReplaceWith)        Dim s As String = sb.ToString        Return s    End Function

 

 



#4 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 14 April 2013 - 07:49 PM

Hello Martin.

 

Thank you for replying. I have tried the Thread.Sleep(200); and Thread.Sleep(300); at different places in the code but it does not seem to give any result. If you don't mind could you instruct me on which line I should insert this?

I have tried below line 25, line 30, line 38, line 39, line 44 and line 81.

 

I never heard of NetworkStreams  :)  If that is considered to be better than I will try to find some working examples so I can see the differences.

I was already happy I got this kind of working.


Netduino Plus 2 (v4.2.2.2)


#5 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 14 April 2013 - 07:52 PM

Thanks for the example Baxter.

I going to look over my code and apply your example to improve my code


Netduino Plus 2 (v4.2.2.2)


#6 martin2250

martin2250

    Advanced Member

  • Members
  • PipPipPip
  • 37 posts
  • LocationGermany

Posted 14 April 2013 - 08:03 PM

I'd try line 81, but baxter is right, you should set the content's length after you' ve finished editing it, because your browser will only read the first ("Hello World".Length.ToString()) characters of the stream. So just moving all "response +=" thingies to line 52 and it should work. another thing: why would you declare the response as "Hello World" and later in your code overwrite it without any conditions... not very optimized ;)

 

regarding NetworkStreams: you can just make them like this 

NetworkStream stream = new NetworkStream(socket);

 

and they give you acess to reading/writing like you would with a FileStream (just in case you like this way more than just having Sockets) also it will be easier to port it over to normal .NET applications, since the TCPClient in System.Net.Sockets does not support writing without requesting the NetworkStream by client.GetStream().



#7 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 14 April 2013 - 08:06 PM

I disabled 2 lines in the code and now it works. The question is now... do I need this code for receiving url requests to control i/o ports?

The lines i Disabled are:

//string header = "HTTP/1.0 200 OKrnContent-Type: text; charset=utf-8rnContent-Length: " + response.Length.ToString() + "rnConnection: closernrn";//clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);

Netduino Plus 2 (v4.2.2.2)


#8 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 14 April 2013 - 08:09 PM

Hi Martin, I totally agree with "why would you declare the response as "Hello World" and later in your code overwrite it without any conditions... not very optimized" I removed it now :) (leftover from copy and pasting code)


Netduino Plus 2 (v4.2.2.2)


#9 martin2250

martin2250

    Advanced Member

  • Members
  • PipPipPip
  • 37 posts
  • LocationGermany

Posted 15 April 2013 - 04:28 PM

no, you don't really need this line, most browsers nowadays should work without a header.

 

for parsing url requests, you can just use my code and modify it for your needs:

netstream = new NetworkStream(client);			byte[] data = new byte[2000];			int readbytes = 0;			while (netstream.DataAvailable)			{				readbytes += netstream.Read(data, readbytes, data.Length - readbytes);			}			string s = new string(ENCD.GetChars(data));			if(s != null && s.Substring(0, 3) == "GET")			{				request = s.Substring(4, s.IndexOf(' ', 4) - 4);                        }

 

if you want, you can also take a look at my server, you might find some things that are useful for your further coding :)

 

Greets



#10 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 15 April 2013 - 06:48 PM

Thanks Martin! Much appreciated.


Netduino Plus 2 (v4.2.2.2)


#11 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 15 April 2013 - 08:58 PM

Hi Martin.

 

I downloaded your code example (Webserver.zip) from http://forums.netdui...lem/#entry45239 I installed it on my Netduino +2. Unfortunately I'm not able to connect to it through my browser (main page does not load for me). I find your code very clean and it looks very interesting.

 

For example, I see a separate HtmlPage.cs and when I look at the code inside it (please correct me if I'm wrong) I think that makes the main html file run in a loop so you get live data on your webserver without the need to refresh the page right?

 

It looks very nice!


Netduino Plus 2 (v4.2.2.2)


#12 martin2250

martin2250

    Advanced Member

  • Members
  • PipPipPip
  • 37 posts
  • LocationGermany

Posted 16 April 2013 - 06:20 PM

hi,

 

thank you, always nice to see some interest in my project.

The class HtmlPage is only intended for easier formatting, so you don't need to include <head></head> and all the other tags that are always present in your main code. You still have to refresh the page in your browser to see new content.

I guess you do have a SD card with some sample files in your netduino. if it still doesn't work, you should replace the function that sends contents with your own one and just make it send back a small page. Also you should of course do some debugging, if i remember correctly your netduino should print a message with the request every time a device connects to it.

 

Greetings,

 

Martin



#13 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 17 April 2013 - 04:54 PM

Thanks Martin!

 

I'm grateful that you shared the code for other people to learn from it. I will experiment until I get it working.

 

Kind regards,

Sebastiaan


Netduino Plus 2 (v4.2.2.2)


#14 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 17 April 2013 - 05:47 PM

Hello Martin.

 

Just to let you know that I got it all working (no changes made). I must have entered the wrong ip address in my browser. I even got it to work with DDNS. So I'm really grateful.

 

Vielen Dank :)


Netduino Plus 2 (v4.2.2.2)


#15 martin2250

martin2250

    Advanced Member

  • Members
  • PipPipPip
  • 37 posts
  • LocationGermany

Posted 18 April 2013 - 01:09 PM

Bitte Sebastiaan :D

 

If you decide to host a website with DDNS, please let me know so I can give it a visit.

 

Greetings



#16 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 18 April 2013 - 03:18 PM

Hi Martin.

 

As I used the exact same code as you posted on http://forums.netdui...server-problem/, I also have the exact same problem :)  (that I need to have it run from Visual Studio). I read on the above link that you found a solution for this with a new line of code "Thread.Sleep(20);".

 

Now that I read your post again, I see that this problem was related to the SD card? I'm not at home yet but I think I'm using a micro SDHC card with more than 2GB (8 or 16GB). As the storage on the netduino + 2 suports up to 2GB, this might be the problem (I was able to read the files on the Netduino). I will experiment with a regular SD card of max 2GB to see if it makes any difference :)

 

Kind regards,

Sebastiaan


Netduino Plus 2 (v4.2.2.2)


#17 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 18 April 2013 - 05:44 PM

No, I have a 256mb SD card from Sandisk. I also have this problem with the updated version in the same post. Do you recall how you got the problem solved?


Netduino Plus 2 (v4.2.2.2)


#18 martin2250

martin2250

    Advanced Member

  • Members
  • PipPipPip
  • 37 posts
  • LocationGermany

Posted 18 April 2013 - 06:36 PM

no, I recently read that post again and tried remembering, but my memory isn't very good sadly.

 

the only things I think I can remember are deleting all files and reformatting the sd card, but I don't know if that was the solution.



#19 sebswed

sebswed

    Advanced Member

  • Members
  • PipPipPip
  • 45 posts
  • LocationSweden

Posted 19 April 2013 - 03:56 AM

Hi Martin.

 

I tried that yesterday evening after reading your message. Deleted the Fat16 partition and created a new Fat16 partition added some files. Same result. I than deleted the Fat16 and created a Fat32. Same result. :)

 

Don't worry about it. I will try to get it work by commenting out some code and see if it changes things. That will not be before Tuesday as I'm away for a couple of days :)

 

Kind regards,

Sebastiaan


Netduino Plus 2 (v4.2.2.2)


#20 marksmanaz

marksmanaz

    Member

  • Members
  • PipPip
  • 15 posts

Posted 11 May 2013 - 05:39 PM

sebswed,

What firmware version are you using on your Netduino Plus 2? Are you having any difficulty getting your device to respond to request outside of its sub net? I created my own web server as well using VB and cannot get a consistent response from Netduino. I also loaded you code and it does the same thing.

 You can find my post about my dilemma here: http://forums.netdui...s-2-web-server/

 

Any input would be appreciated.

 

Thanks,

Mark







0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.