473,549 Members | 2,635 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a simple http server

hi,
i am creating an simple http server ie it serves only static pages .
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.
also i want that the program should continiously listen on the port and
send data to more than one client

also is it possible to invoke a thread that calls a function with
arguments
using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Net;
using System.Net.Sock ets;
using System.IO;
using System.Threadin g;

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(logf ile, FileMode.Append );
StreamWriter sw = new StreamWriter(fi le);
switch (type)
{
case msg.ERROR: logbuffer = "Error: " + s1 +" "+ s2 + "
exiting ";
sw.WriteLine(lo gbuffer);
sw.WriteLine();
sw.Close();
break;
case msg.SORRY: logbuffer = "sorry: " + s1 + " " + s2 + "
";
sw.WriteLine(lo gbuffer);
//add funtion to send data to user;
sw.WriteLine();
sw.Close();
break;
case msg.LOG: logbuffer = "info: " + s1 + " " + s1 + " ";
sw.WriteLine(lo gbuffer);
sw.WriteLine();
sw.Close();
break;
}
if (type == msg.ERROR || type == msg.SORRY)
{
System.Environm ent.Exit(0);
}

}
public static extn[] fileextsused( )
{
extn []extentions =new extn[10];
extentions[1].ext= "gif";
extentions[1].filetype="imag e/gif" ;
extentions[2].ext="jpg";
extentions[2].filetype="imag e/jpeg";
extentions[3].ext="png";
extentions[3].filetype= "image/png";
extentions[4].ext="zip";
extentions[4].filetype="imag e/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.Unicod e;
byte [] rbuffer =new byte[BUFSIZE+1];//recieve buffer
byte [] sbuffer =new byte[BUFSIZE+1];//data to be send
byte[] header = enc.GetBytes("H TTP/1.0 200
OK\r\nContent-Type: %s\r\n\r\n");//http header
string str="<HTML><BOD Y><H1>nweb Web Server
Sorry:</H1></BODY></HTML>\r\n";//actual page

sbuffer = enc.GetBytes(st r);
suck.Receive(rb uffer);
suck.Send(heade r);
suck.Send(sbuff er);

}

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(a rgs[1]);

int i=0;
extn []extentions =new extn[10];
extentions=file extsused();
if (args.Length <2 || args.Length >2 || args[0] == "/?")
{
Console.WriteLi ne("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<exten tions.Length;i+ +)
{

Console.WriteLi ne("\t"+extenti ons[i].ext+"\t"+exten tions[i].filetype+"");
}

Console.WriteLi ne("\n\tNot Supported: URLs including
\"..\",Java, Javascript, CGI\n"+
"\tNot Supported: directories \n\tc:\\ " + "\n\t"
+
Environment.Get FolderPath(Envi ronment.Special Folder.System)+ "\n\t"

+Environment.Ge tFolderPath(Env ironment.Specia lFolder.Program Files) +
"\n\t"
+
Environment.Get FolderPath(Envi ronment.Special Folder.Personal ) + "\n\t"
+
Environment.Get FolderPath(Envi ronment.Special Folder.CommonPr ogramFiles)+"\n "
+"\tNo warranty given or implied\n\tUmes h Tangnu
um**********@gm ail.com\n");
Console.ReadLin e();
System.Environm ent.Exit(0);
}

else
{
if ((args[1] ==
Environment.Get FolderPath(Envi ronment.Special Folder.System)) ||
(args[1] ==
Environment.Get FolderPath(Envi ronment.Special Folder.Personal )) ||
(args[1] ==
Environment.Get FolderPath(Envi ronment.Special Folder.ProgramF iles)))
{
Console.WriteLi ne("ERROR: Bad top directory "+
args[1]+" see nweb /?\n");
Console.ReadLin e();

System.Environm ent.Exit(0);
}
if(!dir.Exists)
{
Console.WriteLi ne("ERROR : Top Directory
"+args[1]+" doesnot exist");
Console.Read();
System.Environm ent.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.Pars e("192.168.1.2" );
IPEndPoint ipe = new IPEndPoint(iadd , port);
Socket sock = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
sock.Bind(ipe);
sock.Listen(32) ;
sock = sock.Accept();
web(sock);
sock.Shutdown(S ocketShutdown.B oth);
sock.Close();
}
}

Dec 1 '05 #1
1 3345
I can't help with the headers issue (I just use HttpListener to do this via
HTTP.SYS), however re the threading Q:

I usually do this by creating a class with some properties (representing the
params), setting the params against an instance and then using a void
Start() method on the instance as the delegate to ThreadStart; my Start
method can then read the params against the same instance. Got this from
MSDN I think (so shouldn't be *too* far from the norm - maybe) - might be
better ways, though...

Marc

"lucifer" <um**********@g mail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
hi,
i am creating an simple http server ie it serves only static pages .
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.
also i want that the program should continiously listen on the port and
send data to more than one client

also is it possible to invoke a thread that calls a function with
arguments
using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Net;
using System.Net.Sock ets;
using System.IO;
using System.Threadin g;

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(logf ile, FileMode.Append );
StreamWriter sw = new StreamWriter(fi le);
switch (type)
{
case msg.ERROR: logbuffer = "Error: " + s1 +" "+ s2 + "
exiting ";
sw.WriteLine(lo gbuffer);
sw.WriteLine();
sw.Close();
break;
case msg.SORRY: logbuffer = "sorry: " + s1 + " " + s2 + "
";
sw.WriteLine(lo gbuffer);
//add funtion to send data to user;
sw.WriteLine();
sw.Close();
break;
case msg.LOG: logbuffer = "info: " + s1 + " " + s1 + " ";
sw.WriteLine(lo gbuffer);
sw.WriteLine();
sw.Close();
break;
}
if (type == msg.ERROR || type == msg.SORRY)
{
System.Environm ent.Exit(0);
}

}
public static extn[] fileextsused( )
{
extn []extentions =new extn[10];
extentions[1].ext= "gif";
extentions[1].filetype="imag e/gif" ;
extentions[2].ext="jpg";
extentions[2].filetype="imag e/jpeg";
extentions[3].ext="png";
extentions[3].filetype= "image/png";
extentions[4].ext="zip";
extentions[4].filetype="imag e/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.Unicod e;
byte [] rbuffer =new byte[BUFSIZE+1];//recieve buffer
byte [] sbuffer =new byte[BUFSIZE+1];//data to be send
byte[] header = enc.GetBytes("H TTP/1.0 200
OK\r\nContent-Type: %s\r\n\r\n");//http header
string str="<HTML><BOD Y><H1>nweb Web Server
Sorry:</H1></BODY></HTML>\r\n";//actual page

sbuffer = enc.GetBytes(st r);
suck.Receive(rb uffer);
suck.Send(heade r);
suck.Send(sbuff er);

}

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(a rgs[1]);

int i=0;
extn []extentions =new extn[10];
extentions=file extsused();
if (args.Length <2 || args.Length >2 || args[0] == "/?")
{
Console.WriteLi ne("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<exten tions.Length;i+ +)
{

Console.WriteLi ne("\t"+extenti ons[i].ext+"\t"+exten tions[i].filetype+"");
}

Console.WriteLi ne("\n\tNot Supported: URLs including
\"..\",Java, Javascript, CGI\n"+
"\tNot Supported: directories \n\tc:\\ " + "\n\t"
+
Environment.Get FolderPath(Envi ronment.Special Folder.System)+ "\n\t"

+Environment.Ge tFolderPath(Env ironment.Specia lFolder.Program Files) +
"\n\t"
+
Environment.Get FolderPath(Envi ronment.Special Folder.Personal ) + "\n\t"
+
Environment.Get FolderPath(Envi ronment.Special Folder.CommonPr ogramFiles)+"\n "
+"\tNo warranty given or implied\n\tUmes h Tangnu
um**********@gm ail.com\n");
Console.ReadLin e();
System.Environm ent.Exit(0);
}

else
{
if ((args[1] ==
Environment.Get FolderPath(Envi ronment.Special Folder.System)) ||
(args[1] ==
Environment.Get FolderPath(Envi ronment.Special Folder.Personal )) ||
(args[1] ==
Environment.Get FolderPath(Envi ronment.Special Folder.ProgramF iles)))
{
Console.WriteLi ne("ERROR: Bad top directory "+
args[1]+" see nweb /?\n");
Console.ReadLin e();

System.Environm ent.Exit(0);
}
if(!dir.Exists)
{
Console.WriteLi ne("ERROR : Top Directory
"+args[1]+" doesnot exist");
Console.Read();
System.Environm ent.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.Pars e("192.168.1.2" );
IPEndPoint ipe = new IPEndPoint(iadd , port);
Socket sock = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
sock.Bind(ipe);
sock.Listen(32) ;
sock = sock.Accept();
web(sock);
sock.Shutdown(S ocketShutdown.B oth);
sock.Close();
}
}

Dec 1 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2057
by: Thomas | last post by:
Hi, Sorry for the stupid subject, but here it goes: I need a simple Webserver which can 1. serve xmlrpc-methods 2. send multicast packets on local network to get response from a similar server acting as master on the given network 3. somehow serve a single file using simple http/webserver methods to
2
8376
by: Hazzard | last post by:
I just realized that the code I inherited is using all asp.net server controls (ie. webform controls) and when I try to update textboxes on the client side, I lose the new value of the textbox when submitting the form to update the database. The server doesn't have the client side value any more. It seems to me that as I begin to write the...
2
2362
by: Abel Chan | last post by:
Hi there, I just got an assignment to work on server maintenance. It is a weekly task and we have about 7 production servers running Win2K server. The tasks include but not limited to 1) Find out drive free space for each server’s disk drives (C:, D:, E:, and etc) 2) Report critical errors from the event logs (Application, System,...
7
1490
by: Steven | last post by:
Hello, First, let me state that I am trying to learn asp.net, so I am a beginner. Now on to the issue. I have a webform with a single Textbox and a FileSystemWatcher monitoring a directory for OnCreate events. I am trying to change the text in response to an OnCreate event. I would like to change the Forecolor to red, from black. ...
5
1795
by: Logickle | last post by:
Hi, all. I'm working on an application which requires communicating session info between separate web apps running on the same web server. The out of process server method sounded ideal, and very simple to implement as far as I could tell. So I re-configured my apps' web.config and machine.config files from InProc to StateServer, and...
8
1484
by: Martin Randall | last post by:
Hi, I'm trying to get a simple dataview test page working on my hosted site. The hosted site runs ASP.Net 2.0, no problem. The test page works on my development machine, no problem... but when I upload the published site I get... System.Data.SqlClient.SqlException: An error has occurred while establishing a connection to the server. When...
0
1248
by: Link | last post by:
hello i want to make simple server client system that send data like that one : http://www.eggheadcafe.com/articles/20020323.asp just no console app well i want to make form with 2 buttons 2 text box :
4
118786
by: dba_222 | last post by:
Dear Experts, Ok, I hate to ask such a seemingly dumb question, but I've already spent far too much time on this. More that I would care to admit. In Sql server, how do I simply change a character into a number?????? In Oracle, it is:
2
2171
by: heddy | last post by:
Howdy folks. I am trying to build a web service using the following configuration: I have Windows 2003 Server running in VMware. I have IIS set up on it. I installed the .NET 2.0 package on the server as well. The VMWare server is called W2K3. I created 2 web sites on the server. One called ResetPool, the other called TestReset. The...
1
1807
by: Ted | last post by:
In MS SQL I used the following to create a stored procedure. USE AdventureWorks; GO IF OBJECT_ID ( 'HumanResources.usp_My_Search', 'P' ) IS NOT NULL DROP PROCEDURE HumanResources.usp_My_Search; GO CREATE PROCEDURE HumanResources.usp_My_Search @searchstring varchar(40) AS
0
7462
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7730
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7975
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7492
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6059
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3510
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3491
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1957
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.