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

over run?


  • Please log in to reply
8 replies to this topic

#1 k_madsen

k_madsen

    Member

  • Members
  • PipPip
  • 22 posts
  • LocationEsbjerg Denmark

Posted 30 January 2012 - 08:24 PM

httpserver
this program will show status of the led adress/internal/led but after few second it overrun.

program.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Oz1ldoHttpdServer
{
    public class Program
    {
        public static void Main()
        { // write your code here
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
 
            Blinkingled blinkingled = new Blinkingled(led);
            Thread workerThread = new Thread(blinkingled.run);
            workerThread.Start();

            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp();
            Oz1ldoHttpServer oz1ldohttpserver = new Oz1ldoHttpServer(led);
            oz1ldohttpserver.ListenForRequest();

         }
      }
  }
Oz1ldoHttpdServer.cs
using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Oz1ldoHttpdServer
{
    class Oz1ldoHttpServer : IDisposable
    {
        protected Socket socket = null;   
        //open connection to onbaord led so we can blink it with every request
        protected OutputPort led;
        public Oz1ldoHttpServer(OutputPort ledfrommain)
        {
            //Initialize Socket class
            led = ledfrommain;
            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)
                    {
                        Oz1ldoHandleRequest bearbejddetaljerne = new Oz1ldoHandleRequest(clientSocket, clientIP, led);
                    }
                }
            }
        }
        #region IDisposable Members
        ~Oz1ldoHttpServer()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (socket != null)
                socket.Close();
        }
        #endregion
    }
}

Oz1ldoHandleRequest.cs
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Oz1ldoHttpdServer
{
    class Oz1ldoHandleRequest : IDisposable
    {
        OutputPort ledGem;
        public Oz1ldoHandleRequest(Socket clientSocket, IPEndPoint clientIP, OutputPort led)
        {
            ledGem = led;
            int bytesReceived = clientSocket.Available;
            byte[] buffer = new byte[bytesReceived];
            int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
            string request = new string(Encoding.UTF8.GetChars(buffer));
            if(0 == request.ToLower().IndexOf("get /")) {get(request,clientSocket,clientIP);}                
        }
        
        private void get(string request, Socket clientSocket, IPEndPoint clientIP)
        {
            // internal harcoded code get register and so on
            if (5 == request.ToLower().IndexOf("internal/")) { intern(request, clientSocket, clientIP); }
            else
            {
                if (0 == request.ToLower().IndexOf("get / http/1.1"))
                {
                    //empty request send default text
                    string iptxt = clientIP.ToString();
                    Debug.Print(request);
                    string txt1 = "Senders IP Adress -> ";
                    string txt2 = "\r\n";
                    Debug.Print(txt1 + iptxt + txt2);
                    Debug.Print("200 Default text responece\r\n");
                    //Compose a response
                    string response = "Oz1ldo Test Server";
                    string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
                    clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
                    clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
                }
                else
                {
                    // say somthing or get the code from sd card if there is one
                    //empty request send default text
                    string iptxt = clientIP.ToString();
                    Debug.Print(request);
                    string txt1 = "Senders IP Adress -> ";
                    string txt2 = "\r\n";
                    Debug.Print(txt1 + iptxt + txt2);
                    //Compose a response
                    unknowncmd(request, clientSocket, clientIP);
               }
            }
        }

        private void intern(string request, Socket clientSocket, IPEndPoint clientIP)
        {
            string test = "It is working";
            Debug.Print(test);
            string commando = request.Substring(14);
            if (commando.IndexOf("HTTP") != -1)
            {
                string intcmd = commando.Substring(0, commando.IndexOf("HTTP"));
                switch (intcmd)
                  {
                    case "led ":
                     {
                         string ledstatus;
                         if (ledGem.Read())
                         {
                             ledstatus = " checked=true ";
                         }else
                         {
                             ledstatus = "";
                        }
                         string response = "<HTML><HEAD><META HTTP-EQUIV=CONTENT-TYPE CONTENT=text/html; charset=windows-1252><meta http-equiv= refresh content=1 /><TITLE>Led Status</TITLE><STYLE TYPE=text/css></STYLE></HEAD><BODY LANG=da-DK DIR=LTR><P ALIGN=CENTER STYLE=margin-bottom: 0cm><form><input type=radio name=diode id=lysdiode" + ledstatus + "/>Diode Status<br /></form></P><P AL1IGN=CENTER STYLE=margin-bottom: 0cm><BR></P></BODY></HTML>";
                         string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
                         clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
                         clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
                         Debug.Print(ledstatus);
                     }
                     break;
                    default:
                        unknowncmd( request, clientSocket,  clientIP);
                     break;
                    }
            }
            else unknowncmd(request, clientSocket, clientIP);
        }
        private void unknowncmd(string request, Socket clientSocket, IPEndPoint clientIP)
        {
            Debug.Print("404 file not found\r\n");
            string response = "404 File not found";
            string header = "HTTP/1.0 404 ERROR\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
            clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
            clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
        }
        #region IDisposable Members
        ~Oz1ldoHandleRequest()
        {
            Dispose();
        }
        public void Dispose()
        {

        }
        #endregion
    }
}


#2 Jamie Lewis

Jamie Lewis

    Member

  • Members
  • PipPip
  • 29 posts

Posted 30 January 2012 - 08:37 PM

can you clarify what you mean by overrun? If I understand you correctly it is because you need to make it multi threaded, the faster you can get a connection pushed off to its own thread so the main one can open accept the new connection will increase throughput (within memory extents anyway). hth. Jamie.

#3 k_madsen

k_madsen

    Member

  • Members
  • PipPip
  • 22 posts
  • LocationEsbjerg Denmark

Posted 30 January 2012 - 08:50 PM

can you clarify what you mean by overrun?
If I understand you correctly it is because you need to make it multi threaded, the faster you can get a connection pushed off to its own thread so the main one can open accept the new connection will increase throughput (within memory extents anyway).

hth.
Jamie.


You can get the led status between 2 to 10 times after that you just get error msg as retur.

#4 Jamie Lewis

Jamie Lewis

    Member

  • Members
  • PipPip
  • 29 posts

Posted 30 January 2012 - 09:15 PM

Ok well without knowing what error message is returned my best guess would still be that you need to implement multi threading on the accept connection ...

using (Socket clientSocket = socket.Accept())

Maybe something like ....
  public void ListenForRequest()
        {
            while (true)
            {
                Socket clientSocket = socket.Accept())
                HttpThread ht = new HttpThread(clientSocket);
                Thread T = new Thread(ht.AcceptConnect)
                T.Start();
            }
        }

class HttpThread {

public Socket client;
HttpThread{Socket cli} {client = cli;}

void AcceptConnect() {
using (Socket clientSocket = socket.Accept()) {
//.... ur code here
}
}
}

This way the servers ready to carry on almost immediately and the thread still utilises Using on the socket so will dispose on when the thread dies.

#5 k_madsen

k_madsen

    Member

  • Members
  • PipPip
  • 22 posts
  • LocationEsbjerg Denmark

Posted 30 January 2012 - 09:19 PM

Thx I will trye it. to morrow, night time here in denmark -) regards Kim

#6 ErikN

ErikN

    Advanced Member

  • Members
  • PipPipPip
  • 119 posts
  • LocationNew York, NY

Posted 30 January 2012 - 10:59 PM

night time here in denmark




I'm going to have to start a list of Scandinavian users! Of which I'll only be an honorary member.


-Erik

#7 k_madsen

k_madsen

    Member

  • Members
  • PipPip
  • 22 posts
  • LocationEsbjerg Denmark

Posted 31 January 2012 - 11:03 AM

Hi
I changed Oz1ldoHttpServer.cs and it works 100%
For completeting the discussion I add the new class.

using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Oz1ldoHttpdServer
{
    class Oz1ldoServerThread
    {
        public Socket client;
               OutputPort led;

        public Oz1ldoServerThread(Socket cli, OutputPort ledadr)
        {   client = cli; 
            led = ledadr; 
        }

        public void work()
        {
            Debug.Print("Ny server thread \r\n");

                //Get clients IP
                IPEndPoint clientIP = client.RemoteEndPoint as IPEndPoint;
                EndPoint clientEndPoint = client.RemoteEndPoint;
                //int byteCount = cSocket.Available;

                int bytesReceived = client.Available;
                if (bytesReceived > 0)
                {
                    Oz1ldoHandleRequest bearbejddetaljerne = new Oz1ldoHandleRequest(client, clientIP, led);
                }
        }
    }

    class Oz1ldoHttpServer : IDisposable
    {
        protected Socket socket = null;   
        //open connection to onbaord led so we can blink it with every request
        protected OutputPort led;

        public Oz1ldoHttpServer(OutputPort ledfrommain)
        {
            //Initialize Socket class
            led = ledfrommain;
            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)
            {
                Socket clientSocket = socket.Accept();
                Oz1ldoServerThread thread = new Oz1ldoServerThread(clientSocket, led);
                Thread T = new Thread(thread.work);
                T.Start();
            }
 
        }
        #region IDisposable Members
        ~Oz1ldoHttpServer()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (socket != null)
                socket.Close();
        }
        #endregion
    }
}


#8 Jamie Lewis

Jamie Lewis

    Member

  • Members
  • PipPip
  • 29 posts

Posted 31 January 2012 - 01:16 PM

great stuff, glad i could help!

#9 k_madsen

k_madsen

    Member

  • Members
  • PipPip
  • 22 posts
  • LocationEsbjerg Denmark

Posted 08 February 2012 - 11:35 AM

To get the http server running without memory leaks
there is a change to Oz1ldoHttpServer.cs

using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Oz1ldoHttpdServer
{
    class Oz1ldoServerThread
    {
        public Socket client;
               OutputPort led;

        public Oz1ldoServerThread(Socket cli, OutputPort ledadr)
        {   client = cli; 
            led = ledadr; 
        }

        public void work()
        {
                //Debug.Print("Ny server thread \r\n");
           
                //Get clients IP
                IPEndPoint clientIP = client.RemoteEndPoint as IPEndPoint;
                EndPoint clientEndPoint = client.RemoteEndPoint;
                //int byteCount = cSocket.Available;

                int bytesReceived = client.Available;
                if (bytesReceived > 0)
                {
                    try { Oz1ldoHandleRequest bearbejddetaljerne = new Oz1ldoHandleRequest(client, clientIP, led); }
                    catch (System.Exception e)
                    {
                        Debug.Print(e.Message+"\r\n");
                    }
                }
                else
                {
                    Debug.Print("Empty connection \r\n");
                    client.Close();
                }
        }
    }

    class Oz1ldoHttpServer : IDisposable
    {
        protected Socket socket = null;   
        //open connection to onbaord led so we can blink it with every request
        protected OutputPort led;

        public Oz1ldoHttpServer(OutputPort ledfrommain)
        {
            //Initialize Socket class
            led = ledfrommain;
            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(6);
            ListenForRequest();
        }

        public void ListenForRequest()
        {
            while (true)
            {
                try
                {
                    Socket clientSocket = socket.Accept();
                    try
                    {
                        Oz1ldoServerThread thread = new Oz1ldoServerThread(clientSocket, led);
                        Thread T = new Thread(thread.work);
                        T.Start();
                    }
                    catch (System.Exception e)
                    {
                        Debug.Print(e.Message + "\r\n");
                    }
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    Debug.Print(e.Message + "\r\n");
                }
            }
 
        }
        #region IDisposable Members
        ~Oz1ldoHttpServer()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (socket != null)
                socket.Close();
        }
        #endregion
    }
}





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.