Main Site Documentation

Web page host


#1

hi,

i 've gone through tutorial web server http://wiki.tinyclr.com/index.php?title=Webserver and it worked
now i want to add jpg or bitmap image to the web page … how can i do this …i need help

using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

using GHIElectronics.NETMF.FEZ;

namespace web_server
{
public class Program
{
public static void Main()
{

        if (Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Length < 1)  // Call the  network interface on the  board
        {
            Debug.Print("No Active network interfaces. Bombing out.");
            Thread.CurrentThread.Abort();
        }

        
        Microsoft.SPOT.Net.NetworkInformation.NetworkInterface NI = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];     //  retrieve the network interface

        
  

        #region Static IP code
                                                                            
        
       NI.EnableStaticIP("192.168.0.25", "255.255.255.0", "192.168.0.1");       //  use a static IP address
        #endregion


       Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);      // Creates the Socket to send data over a TCP connection   

        
        IPAddress hostIP = IPAddress.Parse(NI.IPAddress);           // Bind the listening socket to the port
        IPEndPoint ep = new IPEndPoint(hostIP, 80);
        listenSocket.Bind(ep);


        listenSocket.Listen(1);      // Start listening Socket  for incoming connection attempts.

        while (true)
        {
            try
            {
                Debug.Print("listening...");
                Socket newSock = listenSocket.Accept();
                Debug.Print("Accepted a connection from " + newSock.RemoteEndPoint.ToString());

                string s = "<html>\n";  // creae the web page.
                s += "<head><title>Welcome</title></head>\n";
                s += "<META http-equiv=\"REFRESH\" content=\"60;URL=" + NI.IPAddress + "\">";
                s += "<body>\n";
                s += "<p>Hello, This is the FEZ Cobra Test Page!</p>\n";
                s += "</body>";
                s += "</html>";
                
                byte[] messageBytes = Encoding.UTF8.GetBytes(s);
                newSock.Send(messageBytes);
                newSock.Close();
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
            }
        }
    }

}

}


#2

You can use HTML to display a external bitmap or send a binairy webpage.

The html way:
http://www.w3schools.com/tags/tag_img.asp

The binairy way:
http://code.tinyclr.com/project/243/webserver-extension-for-fez-cobra/

private static void sendResource(object sender, HttpServer.EventCallbackEventArgs e)
        {
            e.BinaryResponse = Resources.GetBytes(Resources.BinaryResources.mySwfFile);
            e.ResponseContentType = "application/x-shockwave-flash";
        }

For more info wouter can help you with that server.

Edit: You can also store them on a sd card.


#3

You can store the jpeg file on an SD card and read it in when you received a request.

Both these code projects will show you how to do that:

http://www.tinyclr.com/forum/23/5551/

http://www.tinyclr.com/forum/23/5478/


#4

@ max12 - please use code tags. makes your post much easier to read.


#5

thank all for support.


#6

hi,

i’m putting the web page in to resources and now in getting the web page i created by entering the ip address but problem is that im not able to see any pictures of the web site…
any suggetions ?

regards.


#7

@ max12

If you put that web page and image file on a normal server does it render correctly?

Also, are you setting the correct “content-coding”?

Please post a segment of the html code from your web page where the file is referenced.
It could be that the path is incorrect.


#8

@ jasdev

do i need to encode pictures in my web page from and give the referenced path of the images from C#?
how to give referenced path and encode from C#

 <p align="center"><img src="file:///path/Visual Studio 2010/Projects/ web server/ web server/Resources/New folder/h641_beng_dce.jpg" width="291" height="150"></p>

regards.


#9

@ max12

The path to the file that is coded into your html should NOT be a physical path on your hard disk.
It should be a relative url from the root of your web site.
For example:


#10

ok
got it…
and do i need to encode those images in my programme.

regards.


#11

The content type in your response should be set as follows:

contentType = "image/jpeg"

You shouldn’t need to encode the image bytes. Here is an example of how I send a file that is stored on the SD card. You can use a similar approach for sending bytes from a resource.

using (FileStream input = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
	httpResponse.ContentLength64 = input.Length;
	byteBuffer = new byte[512];
	while (true)
	{
		bytesRead = input.Read(byteBuffer, 0, byteBuffer.Length);
		if (bytesRead == 0) break;
		httpResponse.OutputStream.Write(byteBuffer, 0, bytesRead);
	}
}

#12

i try to put image in to resource and
put this into code

case "image":


                   Pic = Resources.GetBitmap(Resources.BitmapResources.image);
            break;
          else 
{
 Bitmap = Encoding.UTF8.GetBytes(Bitmap);}

same resultls … why from this method we cannot get images.

regards.


#13

@ max12

In order to do what you want, you should be using a more sophisticated web server like this one from Wouter:

http://www.tinyclr.com/forum/23/5551/

You then need to store your image file in Resources as a BinaryResource so that you can retrieve it with GetBytes. Once you have an array of bytes you can pass that to Wouter’s web server and it will send them back to the client.


#14

@ jasdev

when i try to return GIF image in resources with

public   static void getrequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            string str = GetpathfromUrl(request.RawUrl);
          Bitmap buf = Resources.GetBitmap(Resources.BitmapResources.image1);


            if (context.Request.RawUrl == "/image.gif")
            {
                context.Response.ContentType = "images/jpeg";

                  context.response.OutputStream.Write(Resources.GetBitmap(Resources.BitmapResources.image1));
           
                
            }
      }

Is this the wite method to get image from resources.
it giives me error “No overload for method ‘Write’ takes 1 arguments” although i put correct references.i really dont understand what 's wrong there because im bad with codings

regards,


#15

if you’re “bad with codings” then you should take someone else’s code as-is and not change it. It’s probably better that you take Wouter’s code like you were pointed to before, as it works and you can step through it and start to understand the code you’re writing.

In this case, what that message is telling you is that the WRITE method needs more parameters, as you have only supplied one parameter - your parameter is:

Resources.GetBitmap(Resources.BitmapResources.image1)

Use Intellisense and it will point out what the parameters of this call is, from memory you need an offset from the start of your buffer to start sending data, and then the number of bytes to send.


#16

@ max12

context.Response.OutputStream.Write

is defined as follows:


public virtual abstract void Write (
         byte[] buffer,
         int offset,
         int count
)

It requires three parameters: a byte[] buffer, an offset, and a count.


#17

hi,
I tried with store web page in the sd card and receive it .it works fine but still gif images are not display… is this the correct method to show images in the web page.

static void ContentTypeFromName(HttpListenerContext context,string strfilepath)
 {    
   ;
    HttpListenerResponse response =context.Response;
     if(strfilepath.IndexOf(".Gif")!=-1)
         
     {
         response.ContentType = "image";
     }

 }    

    

 public static byte[] ImageToBinary(string imagePath)  // convert image to binary
 {
     string rootdirectory=VolumeInfo.GetVolumes()[0].RootDirectory;
     FileStream fileStream = new FileStream(rootdirectory + @ "\image11.gif", FileMode.Open, FileAccess.Read); 
     
   
     byte[] buffer = new byte[fileStream.Length];
     fileStream.Read(buffer, 0, buffer.Length);

     fileStream.Close(); 
     return buffer;
 }

regards.


#18

Hi,
I think the content type should be

contentType = "image/gif"

To send it back to the client’s browser, you’ll need to do something like this:


// send file
httpResponse.StatusCode = (int)HttpStatusCode.OK;
httpResponse.ContentType = "image/gif";

// send file to client
using (FileStream input = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
	httpResponse.ContentLength64 = input.Length;
	byteBuffer = new byte[512];
	while (true)
	{
		bytesRead = input.Read(byteBuffer, 0, byteBuffer.Length);
		if (bytesRead == 0) break;
		httpResponse.OutputStream.Write(byteBuffer, 0, bytesRead);
	}
}

#19

@ jasdev
hi

i hv done all things to retreive the image but it keep saying blank where image want to dispaly…whr i made mistake… i need help
and here is my code.

public class Program
    {
    
             

        static PersistentStorage sdps;
        public static void Main()
        {


            if (Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Length < 1)
            {
                Debug.Print("No Active network interfaces");
                Thread.CurrentThread.Abort();
            }
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface NI = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];
            NI.EnableStaticIP("ipadd", "subnet mask", "d.gatway");

            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress hostIP = IPAddress.Parse(NI.IPAddress);
            IPEndPoint ep = new IPEndPoint(hostIP, 80);
            server.Bind(ep);


            Debug.Print("insert ");

            if (PersistentStorage.DetectSDCard())

                Debug.Print(" detect");

            {
            
                {


                    sdps = new PersistentStorage("SD");
                   
                    sdps.MountFileSystem();
                  
                    if (VolumeInfo.GetVolumes()[0].IsFormatted)
                    {
                        server.Listen(1);
                        while (true)
                        {

                            Debug.Print("ready.....");
                            Socket clientSocket = server.Accept();
                            new ProcessClientRequest(clientSocket, true);
                        }

                    }
                    else
                    {
                        Debug.Print("please format");
                    }
                    Thread.Sleep(500);
                    sdps.UnmountFileSystem();

                }

            }
        }


        public static void ContentTypeFromName(HttpListenerResponse serverresponse, string strfilepath)// to get the image
       {
            byte[] bytebuffer = null;
            int bytesRead = 0;
            serverresponse.StatusCode = (int)HttpStatusCode.OK;
            serverresponse.ContentType = "image/gif";

            string rootdirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
            using (FileStream input = new FileStream(rootdirectory + @ "\pic1.gif", FileMode.Open, FileAccess.Read))
            {
                serverresponse.ContentLength64 = input.Length;
                bytebuffer = new byte[512];
                while (true)
                {
                    bytesRead = input.Read(bytebuffer, 0, bytebuffer.Length);           
                    if (bytesRead == 0) break;
                    serverresponse.OutputStream.Write(bytebuffer, 0, bytesRead);
                }
            }
        }



        public static string readpage(string pagefile)// web page
        {

            string rootdirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
            FileStream htmlhandle = new FileStream(rootdirectory + @ "\main.html", FileMode.Open, FileAccess.Read);

            
            byte[] page = new byte[htmlhandle.Length];
            int bytesRead = htmlhandle.Read(page, 0, page.Length);
            htmlhandle.Close();
            return bytesToString(page);
        }


 
        public static string bytesToString(byte[] bytes)
        {
            string s = string.Empty;
            for (int i = 0; i < bytes.Length; ++i)
            {
                s += (char)bytes[i];
            }
            return s;
        }
        internal sealed class ProcessClientRequest
        {
            private Socket m_clientSocket;

            public ProcessClientRequest(Socket clientSocket, Boolean asynchronously)
            {
                m_clientSocket = clientSocket;

                if (asynchronously)

                    new Thread(ProcessRequest).Start();
                else ProcessRequest();
            }

            private void ProcessRequest()
            {
                const Int32 c_microsecondsPerSecond = 1000000;

                using (m_clientSocket)
                {
                    Byte[] buffer = new Byte[1024];
                    if (m_clientSocket.Poll(5 * c_microsecondsPerSecond, SelectMode.SelectRead))
                    {
                        if (m_clientSocket.Available == 0)
                            return;
                        Int32 bytesRead = m_clientSocket.Receive(buffer, m_clientSocket.Available, SocketFlags.None);

                        string s = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n";
                        s += readpage(@ "\main.html");
                        m_clientSocket.Send(Encoding.UTF8.GetBytes(s));
                        
                    }
                }
            }
        }
    }
}

#20

@ max12
Your code never downloads the image file to the client.
Your ProcessClientRequest is hardcoded to download the html file every time.
You should modify your code to look at the request.url to determine which file the client is requesting, and then download that file.

The client browser will first request the html file, and then after it is parsed, it will determine that you have an embedded image, and will then request the image file from your web server.