Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Nov 27th, 2005, 12:40 PM   #1
lucifer
Programmer
 
lucifer's Avatar
 
Join Date: Oct 2005
Posts: 84
Rep Power: 3 lucifer is on a distinguished road
http server in c#

hi,
i am creating a http server for my college project . It is very simple as the server will be only used to serve static pages .
Quote:
There are only a few functions in the source code, explained below.

log()
Logs messages to a log file. If the user requests an operation from the Web server that is not allowed or can't be completed, then nweb tries to inform the user directly. This is done by returning a fake Web page to the user that includes the error message. If this is not a recoverable error, then the process is stopped.
web()
Deals with the HTTP browser request and returns the data to the browser. This function is called in a child process -- one for each Web request. It also allows the main Web server process to continue waiting for more connections. Checks are made to ensure the request is safe and can be completed. After the checks have been made, it transmits the requested static file to the browser and exits.
main()
This is the main Web server process function. After checking the command parameters, it creates a socket for incoming browser requests, sits in a loop accepting request.
limitations of the project(due to my limited knowledge of c# ):
1 serves only static files .
2 single client supported(i dont know multi threading).

so plz help me in completing this project
code written so far
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;


    class Program
    {
    static int BUFSIZE= 8096;
    static int ERROR =42;
    static int SORRY =43;
    static int LOG = 44;
       static void log(int type,string s1,string s2)
    {
        int fd;
         string logbuffer;
         FileStream file = new FileStream("http.log", FileMode.Append);
         StreamWriter sw = new StreamWriter(file);
         switch (type)
         {
             case 42: logbuffer = "Error: " + s1 +" "+ s2 + " exiting ";
                 sw.WriteLine(logbuffer);
                 sw.WriteLine();
                 sw.Close();
                 break;
             case 43: logbuffer = "sorry: " + s1 + " " + s2 + " ";
                 sw.WriteLine(logbuffer);
                 //add funtion to send data to user;
                 sw.WriteLine();
                 sw.Close();
                 break;
             case 44: logbuffer = "info: " + s1 + " " + s1 + " ";
                 sw.WriteLine(logbuffer);
                 sw.WriteLine();
                 sw.Close();
                 break;
         }
         if (type == 42 || type == 4)
         {
             //write code that will exit the program till better option of multithreading
         }

         
        
    }
        static void Main(string[] args)
        {
            log(ERROR,"no file","user");
        }
    }
lucifer is offline   Reply With Quote
Old Nov 27th, 2005, 2:17 PM   #2
Dameon
Troll
 
Dameon's Avatar
 
Join Date: Apr 2005
Location: Texas
Posts: 730
Rep Power: 4 Dameon is on a distinguished road
Multithreading is not needed to serve multiple clients. It can be as simple as having an array of connected clients (A connected client being state information and a socket) that you loop through and process at a set interval.
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270
Dameon is offline   Reply With Quote
Old Nov 27th, 2005, 2:41 PM   #3
lucifer
Programmer
 
lucifer's Avatar
 
Join Date: Oct 2005
Posts: 84
Rep Power: 3 lucifer is on a distinguished road
Quote:
Originally Posted by Dameon
Multithreading is not needed to serve multiple clients. It can be as simple as having an array of connected clients (A connected client being state information and a socket) that you loop through and process at a set interval.
thanks
well my next problem is to exit the program when an error happens
also how should i get the path to the directories where windows installed or where temp dir is or the document folder
static void Main(string[] args)
        {
            int i=0;
            extn []extentions =new extn[10];
			extentions=fileextsused();
            if (args.Length < 3 || args.Length > 3 || args[1] == "/?") 
            {
                Console.WriteLine("hint: nweb Port-Number Top-Directory\n\n"+
        "\tnweb is a small and very safe mini web server\n"+

        "\tnweb only servers out file/web pages with extensions named 
below\n"+       "\t and only from the named directory or its sub-directories.\n"+

        "\tThere is no fancy features = safe and secure.\n\n"+

        "\tExample: nweb 8181 c:\\web &\n\n"+

        "\tOnly Supports:");
                for(i=0;i<extentions.Length;i++)
                {
                    Console.WriteLine(extentions[i].ext+"\t"+extentions[i].filetype+"\n");
                }

                Console.WriteLine("\n\tNot Supported: URLs including \"..\",Java, Javascript, CGI\n"+ 
                    "\tNot Supported: directories c:\\+ $WINDIR+ $TEMP +$My Documents\n"+
       "\tNo warranty given or implied\n\tUmesh Tangnu umeshktangnu@gmail.com\n");
            }
                 
            else
            {
                if ((args[2] == "/") || (args[2] == "/etc") || (args[2] == "/bin") || (args[2] == "/lib") || (args[2] == "/tmp") || (args[2] == "/usr") || (args[2] == "/dev") || (args[2] == "/sbin"))
                {
                    Console.WriteLine("ERROR: Bad top directory "+ args[2]+" see nweb /?\n");
                }
            log(ERROR, "no file", "user");
            }
        Console.ReadLine();
        }
lucifer is offline   Reply With Quote
Old Nov 27th, 2005, 4:07 PM   #4
Dameon
Troll
 
Dameon's Avatar
 
Join Date: Apr 2005
Location: Texas
Posts: 730
Rep Power: 4 Dameon is on a distinguished road
You can use the Environment class to get and manipulate environment variables. Use the ExpandEnvironmentVariables function to replace environment variables enclosed in %

Example:
%TEMP%\HTTP_Logs
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270
Dameon is offline   Reply With Quote
Old Dec 1st, 2005, 2:04 PM   #5
lucifer
Programmer
 
lucifer's Avatar
 
Join Date: Oct 2005
Posts: 84
Rep Power: 3 lucifer is on a distinguished road
code update and new problem

i have almost created the basic part of the server
the updated code is as follows
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

    class Program
    {
    static int BUFSIZE= 8096;
       

    enum msg
    {
    ERROR =42,
    SORRY =43,
    LOG = 44,
        }

       static void log(msg type,string s1,string s2) //used for logging of errors
    {
        string logfile = "http.log";
         string logbuffer;
         FileStream file = new FileStream(logfile, FileMode.Append);
         StreamWriter sw = new StreamWriter(file);
         switch (type)
         {
             case msg.ERROR: logbuffer = "Error: " + s1 +" "+ s2 + " exiting ";
                 sw.WriteLine(logbuffer);
                 sw.WriteLine();
                 sw.Close();
                 break;
             case msg.SORRY: logbuffer = "sorry: " + s1 + " " + s2 + " ";
                 sw.WriteLine(logbuffer);
                 //add funtion to send data to user;
                 sw.WriteLine();
                 sw.Close();
                 break;
             case msg.LOG: logbuffer = "info: " + s1 + " " + s1 + " ";
                 sw.WriteLine(logbuffer);
                 sw.WriteLine();
                 sw.Close();
                 break;
         }
         if (type == msg.ERROR || type == msg.SORRY)
         {
             System.Environment.Exit(0);
         }

         
        
    }
        	public static extn[] fileextsused( )
		{
			extn []extentions =new extn[10];
			extentions[1].ext= "gif"; 
			extentions[1].filetype="image/gif" ;
			extentions[2].ext="jpg";
			extentions[2].filetype="image/jpeg";
			extentions[3].ext="png";
			extentions[3].filetype= "image/png";
			extentions[4].ext="zip";
			extentions[4].filetype="image/zip";
			extentions[5].ext="gz";
			extentions[5].filetype= "image/gz";
			extentions[6].ext="tar";
			extentions[6].filetype= "image/tar";
			extentions[7].ext="htm";
			extentions[7].filetype="text/html";
			extentions[8].ext="html";
			extentions[8].filetype="text/html";
			extentions[9].ext="0";
			extentions[9].filetype="0";
			return extentions;
		
		}
        	public	struct extn
	{
		public String ext;
		public string filetype;
	}
        public static void web(Socket suck ) //used for sending data to the                                                     //client
        {
            Encoding enc = Encoding.Unicode;
            byte [] rbuffer =new byte[BUFSIZE+1];//recieve buffer 
            byte [] sbuffer =new byte[BUFSIZE+1];//data to be send
            byte[] header = enc.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n");//http header
            string  str="<HTML><BODY><H1>nweb Web Server Sorry:</H1></BODY></HTML>\r\n";//actual page
          
          sbuffer = enc.GetBytes(str);
          suck.Receive(rbuffer);
          suck.Send(header);
          suck.Send(sbuffer);

          
            
        }

        static void Main(string[] args)
        {
            DirectoryInfo dir;
            
            args = new string[2];
            args[0] = "80";
            args[1] = @"c:\a";
            int port;
            port = Convert.ToInt32(args[0]);
            dir = new DirectoryInfo(args[1]);
            

            
            int i=0;
            extn []extentions =new extn[10];
			extentions=fileextsused();
            if (args.Length <2 || args.Length >2 || args[0] == "/?") 
            {
                Console.WriteLine("hint: nweb Port-Number Top-Directory\n\n"+
        "\tnweb is a small and very safe mini web server\n"+
        "\tnweb only servers out file/web pages with extensions named below\n"+
        "\t and only from the named directory or its sub-directories.\n"+
        "\tThere is no fancy features = safe and secure.\n\n"+
        "\tExample: nweb 8181\n c:\\web &\n\n"+
        "\tOnly Supports:");
                for(i=0;i<extentions.Length;i++)
                {
                    Console.WriteLine("\t"+extentions[i].ext+"\t"+extentions[i].filetype+"");
                }

                Console.WriteLine("\n\tNot Supported: URLs including \"..\",Java, Javascript, CGI\n"+
                    "\tNot Supported: directories \n\tc:\\ " + "\n\t" 
                    + Environment.GetFolderPath(Environment.SpecialFolder.System)+"\n\t"
                    +Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\n\t" 
                    + Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\n\t" 
                    + Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles)+"\n"
                    +"\tNo warranty given or implied\n\tUmesh Tangnu umeshktangnu@gmail.com\n");
                Console.ReadLine();
                System.Environment.Exit(0);
            }
                 
            else
            {
                if ((args[1] == Environment.GetFolderPath(Environment.SpecialFolder.System)) || (args[1] == Environment.GetFolderPath(Environment.SpecialFolder.Personal)) || (args[1] == Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)))
                {
                    Console.WriteLine("ERROR: Bad top directory "+ args[1]+" see nweb /?\n");
                    Console.ReadLine();
                    System.Environment.Exit(0);
                }
                if(!dir.Exists)
                {
                    Console.WriteLine("ERROR : Top Directory "+args[1]+"  doesnot exist");
                    Console.Read();
                    System.Environment.Exit(0);
                }
                
            }
            if (port < 0 || port > 60000)
                log(msg.ERROR, "Invalid port number (try 1->60000)", args[0]);
            log(msg.LOG, "nweb starting", args[0]);
            
            IPAddress iadd =IPAddress.Parse("192.168.1.2");
            IPEndPoint ipe = new IPEndPoint(iadd, port);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Bind(ipe);
            sock.Listen(32);
            sock = sock.Accept();
            web(sock);
            sock.Shutdown(SocketShutdown.Both);
            sock.Close();                  
        }
    }

u can compile the code then use ur browser if it is IE then the it shows the page but the http header is also shown
HTTP/1.0 200 OK Content-Type: text/html
nweb Web Server Sorry:
but if the browser is mozilla/Firefox it shows the recieved data as an application and tells me to save it.
__________________
"You're good... but me, I'm magic"
lucifer is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 11:50 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC