You are on page 1of 148

Certificate

This is to certify that aforesaid candidates of Bachelor of Computer Application, Aryan Institute of Management & Computer Studies (AIMCS), Agra are bona-fide owners of the project WEB SERVER The project is successfully completed under my supervision and guidance at AIMCS, Agra during the academic session 2009-2010. This is to sign and certify that work is completely original and performed under my guidance.

Mr. Gaurav Arora (Project Guide) Date:

Abstract
A web server is a software application that uses HTTP. When you go for a website under www it seems to be a very easy process as you have put down the name of web page in the address bar and page is displayed in front of you. But actually it is a two sided story. Web servers are responsible for storing and exchanging information with other machines. Because of this, at least two participants are required for each exchange of information: a client, which requests the information, and a server, which stores it. Each side also requires a piece of software to negotiate the exchange of data; in the case of the client, a browser like Netscape or Internet Explorer is used. On the server side, however, things are not as simple. There is a myriad of software options available, but they all have a similar task: to negotiate data transfers between clients and servers via Hypertext Transfer Protocol, the communications protocol of the Web. What type of server software you are able to run depends on the Operating System chosen for the server. For example, Microsoft Internet Information Server is a popular choice for Windows NT, while many UNIX fans choose Apache Web server. A Web Server is software application that uses the Hypertext Transfer Protocol. A Web Server is usually run on a computer that is connected to the Internet. It may be defined as a computer that stores Web documents and makes them available to the rest of the world. A server may be dedicated, meaning its sole purpose is to be a Web server, or non-dedicated, meaning it can be used for basic computing in addition to acting as a server.

Contents
Acknowledgement Certificate Abstract 1. Introduction
1.1 Web Server 1.1.1 How does web server works 1.1.2 Function flow in web server 1.1.3 Functions of web server 1.2 Protocols used in web server 1.2.1 Hyper Text Transfer Protocol (HTTP) 1.2.2 TCP/IP 1.3 HTTP Message Format 1.3.1 HTTP Request message 1.3.2 Types of HTTP Request 1.3.3 HTTP Response Message 1.4 HTTP Methods 1.4.1 Safe Methods 1.4.2 Idempotent Method 1.5 Proxy Server 1.5.1 When Proxy Server are useful 1.6 MIME 1.6.1 MIME Functionality 1.6.2 MIME Header Fields

2. Objective
2.1 Challenges Faced

3. Requirement and Analysis


3.1 Basic Requirement 3.2 what language should be used 3.3 what standards/protocols should be used 3.4Why Java?

3.4.1 Characteristics 3.4.2 Comparison between Modular and Object oriented Technology 3.4.3 Java features used 3.5Hardware and Software requirement 3.6 Functional Requirement 3.6.1 User Interface Requirement 3.6.2 Processing Requirement 3.6.3 Storage Requirement

4. System Modeling
4.1 Functional modeling 4.2 Behavioral Modeling

5. System Design
5.1 User Interface Design 5.2 Output Design

6. Coding 7. Testing 8. Result/Output 9. Limitation 9. Conclusion 11. Future Scope 12. Bibliography

Introduction
Web Server:
A Web Server is software application that uses the Hypertext Transfer Protocol. A Web Server is usually run on a computer that is connected to the Internet. It may be defined as a computer that stores Web documents and makes them available to the rest of the world. A server may be dedicated, meaning its sole purpose is to be a Web server, or non-dedicated, meaning it can be used for basic computing in addition to acting as a server. A web server serves web pages to clients across the Internet or an Intranet. The web server hosts the pages, scripts, programs, and multimedia files and serves them using HTTP, a protocol designed to send files to web browsers and other protocols. Web server is a computer that provides World Wide Web services on the Internet. It includes hardware, operating system, Web server software, TCP/IP protocols and the Web site content (Web pages). If the Web server is used internally and not by the public, it may be known as an "intranet server." When the Web server receives a request from a browser, it passes the request to the WebObjects adaptor, which generates a response and returns it to the Web server. The Web server then sends the response to the browser. There are many Web Server software applications, including public domain software from Apache, and commercial applications from Microsoft, Oracle, Netscape and others. A Web Server may host or provide access to Content and responds to requests received

from Web browsers. The computer program (housed in a computer) that serves requested HTML pages or files. A computer running Web server software and permanently connected to the Internet, dedicated to maintaining web pages on its hard drive; accessible from outside via Internet protocols, hence must have its own DNS address, and thus physically have its own NAM-->port-->hub-->router connection.

How does web server works:


Web server fulfils the request made by the client over the internet. Here is a simple exchange between the client machine and Web server which goes like this: 1. The client's browser dissects the URL in to a number of separate parts, including address, path name and protocol. 2. A Domain Name Server (DNS) translates the domain name the user has entered in to its IP address, a numeric combination that represents the site's true address on the Internet (a domain name is merely a "front" to make site addresses easier to remember). 3. The browser now determines which protocol (the language client machines use to communicate with servers) should be used. Examples of protocols include FTP, or File Transfer Protocol, and HTTP, HyperText Transfer Protocol. 4. The server sends a GET request to the Web server to retrieve the address it has been given. For example, when a user types http://www.bbdnitm.com/1.jpg, the browser sends a GET 1.jpg command to example.com and waits for a response. The server now responds to the browser's requests. It verifies that the given address exists, finds the necessary files, runs the appropriate scripts,

exchanges cookies if necessary, and returns the results back to the browser. If it cannot locate the file, the server sends an error message to the client. 5. The browser translates the data it has been given in to HTML and displays the results to the user. This process is repeated until the client browser leaves the site. The workflow for this is shown here:

Figure 1.1 Work flow of web server Aside from its functions listed above, the Web server also has an additional number of responsibilities. Whereas a Web browser simply translates and displays data it is fed, a Web server is responsible for distinguishing between various error and data types. A Web server must, for example, designate the proper code for any sort of internal error and send that back to the browser immediately after it occurs. It also has to distinguish between various elements on a Web page (such as .GIFs, JPEGS and audio files) so that the browser knows which files are saved in which format. Depending on the site's function, a Web server may also have numerous additional tasks to handle, including logging statistics, handling security and encryption, serving images for other sites (for banners,

pictures, etc), generating dynamic content, or managing e-commerce functions.

Function Flow in the web server:


In the web server before an application can call any socket functions, Windows requires the webserver to be initialized via a call to web().Once server is initialized, a socket can be created to allow two machines to communicate. The term socket describes an end-point of communications through which data can be sent and received. Sockets are created by calling the function socket(). Using a socket differs between client-based and server-based applications. Clients need only call connect() to establish a connection to a server. Servers are also required to further prepare the socket for incoming client connections. Figure 1.2 shows a flow diagram describing the function calls needed for both a server and a client TCP/IP application. Since we are developing a simple web server, we will focus on server-based sockets. Once a socket is created, a server needs to bind the socket using the ServerSocket(int port) function. Binding a socket ties it to a given port and IP address. By providing services on different ports, a machine can host a number of different applications. For instance, it is common to host both FTP and HTTP on the same machine. Typically, HTTP uses port 80 for all incoming client connections; OHM web server is default coded to port 80. Once the port is bound to the socket, the server takes the maximum length of the socket's backlog queue as 50 by default. Since a server must handle simultaneous client connections, the backlog queue allows the server to hold pending client connections until the server can accept them. In OHM, this value has been set to 50, which forces the TCP/IP stack provider to set the maximum backlog value for the socket. The socket is now ready to accept incoming client browser connections. Calling the accept() function causes the server to wait

until a client connection is detected, at which point accept() returns with a new socket specifically for communicating with that client. Using the returned socket and recv(), we can read the HTTP request that the client sent and send back the proper document (HTML, image, etc.) using send(). When an application is through using a socket, the socket must be closed by calling closesocket(). Before the application exits, it must release the Winsock resources via a call to WSACleanup().

Figure 1 - Function Flow

Functions of Web Server:


At a very basic level, Web servers serve simple, static content -HTML documents and images. Users request for files through browsers which is picked up by the Web server and taken to the host file system. The desired file is loaded from the disk where it travels back across the network and is finally delivered to the Web browser by the Web server.

Hypertext Transfer Protocol (HTTP)


The browser and the Web serer talk to each other using Hypertext Transfer Protocol (HTTP). A single TCP connection is opened that transmits first the HTML document and then images, one-by-one, in an efficient manner.

Hypertext Transmission Protocol, Secure (HTTPS)


HTTPS is a security protocol that allows a secure Web connection. This means that with HTTPS it is safe for an exchange of sensitive data between user and the server across the insecure network. URLs that begin with 'https' are handled using SSL algorithm (now commonly termed as Transport Level Security - TLS) that setup a secure, encrypted link between a Web browser and a Web server.

Multipurpose Internet Mail Extension (MIME)


MIME type header is the primary mechanism to display content downloaded by the browser. It tells browser about the content type being delivered. MIME types are identified using a type/subtype syntax associated with a file extension. Here are some examples: text/xml xml video/mpg mpeg mpg video/quicktime qt mov

Serving Web Pages Today's Web servers are able to process and deliver multiple requests in a simultaneous manner to serve more users at a time. This concurrency is realized in two different ways: multi-threading and multi-processing. Today's most Web sites run Web servers that support either multi-threading or multi-processing and thus can handle a much higher load.

Protocols used in the web server


Protocols are the set of rules which must be followed during transmission of message from one communication device to another. Some of the common protocols which are followed in the web server are as follows:

Hyper Text Transfer Protocol


The Hypertext Transfer Protocol (HTTP), the Web's application-layer protocol, is at the heart of the Web. HTTP is implemented in two programs: a client program and server program. The client program and server programs, executing on different end systems, talk to each other by exchanging HTTP messages. HTTP defines the structure of these messages and how the client and server exchange the messages. HTTP is a protocol used mainly to access data on the WWW .the protocol transfers data in the form of a plain text, hypertext, audio, and video and so on. However it is called hypertext transfer protocol because its efficiency allows its use in a hypertext environment where there are rapid jumps from one document to another. HTTP functions like a combination of FTP and SMTP. It is similar to FTP because it transfers file s and uses the services of TCP.however it is simpler than FTP because it uses only one TCP

connection. There is not a separate control connection only data are transferred between the client and server. HTTP is like SMTP because the data transferred between the client and server look like SMTP messages. In addition, the format of the message is controlled by MIME like header. However HTTP differs from SMTP in the way the message are sent from the server to the client and from client to the server. Unlike SMTP HTTP message can not to be destined to be read by humans, they are read by humans; they are read and interpreted by the HTTP server and HTTP client. The idea behind HTTP is very simple .a client sends a request which looks like mail to the server. The server sends the response, which looks like a mail reply to the client. The request and response messages carry data in the form of a letter with MIME like format. The HTTP client first initiates a TCP connection with the server. Once the connection is established, the browser and the server processes access TCP through their socket interfaces. The client sends HTTP request messages into its socket interface and receives HTTP response messages from its socket interface. Similarly, the HTTP server receives request messages from its socket interface and sends response messages into the socket interface. Once the client sends a message into its socket interface, the message is "out of the client's hands" and is "in the hands of TCP".

Figure 1.3: HTTP request-response behavior

HTTP 1.0 is a fast, stateless protocol for the exchange of textual information. "Stateless", in this context, means that the server doesn't remember any information about a query after it has been responded to HTTP, however, is amnesiac; if you send two commands to an HTTP server, the result of the first command should not in any way affect the second command (except in some limited, unusual, circumstances: for example, when a CGI script is tracking state information associated with a browser's interaction with the server).

TCP/IP
TCP/IP protocol suite used in the internet was developed prior to the OSI model .it consists of five layers: physical, data

link, network, transport, and application. The first four layers provide physical standards, network interface, internetworking, and transport functions that correspond to the first four layers of the OSI model. TCP/IP is a hierarchical protocol made up of interactive modules each of which provides a specific functionality, but they are not necessarily interdependent.TCP/IP protocol suite contain relatively independent protocols that can be mixed and matched depending on the need of the system. The term hierarchical means that each upper level protocol is supported by one or lower layer protocols. At the transport layer TCP/IP defines two protocols: Transmission control protocol (TCP) and User Datagram protocol(UDP).at the network level the main protocol defined by TCP/IP is Internetworking Protocol(IP). TCP provides full transport layer service to the application.TCP is a reliable stream transport port to port protocol. The term stream in this context means connection oriented: a connection must be established between both ends of a transmission before either may transmit data. By creating this connection, TCP generates a virtual circuit between sender and receiver that is active for the duration of transmission.TCP begins each transmission by altering the receiver that datagram are on the way and ends each transmission with a connection termination. TCP provides reliable delivery which is ensured by provision for error detection and retransmission of damaged frames; all segments must be received and acknowledged before the transmission is considered complete and the virtual circuit is discarded. At the sending end of each transmission, TCP divides long transmission into smaller data units and packages each into a

frame called a segment. Each segment includes a sequencing number for recording after receipt ,together with an acknowledgement ID number and a window size field for sliding window ARQ. Segments are carried across network links inside of IP datagrams.at the receiving end TCP collects each datagram as it comes in and reorders the transmission based on the sequence numbers. IP is the transmission mechanism used by the TCP/IP protocols. it is an unreliable and connectionless datagram protocol-a best effort delivery service. the term best effort means that IP provides no error checking or tracking .IP assumes the unreliability of the underlying layers and does its best to get a transmission through to its destination but with no guarantees.IP transports data in the form of packets called datagrams each of which transported separately.datagrams may transported separately.datagrams may travel along different routes and may arrive out of sequence or duplicated.IP does not keep track of the routes and has no facility for reordering datagrams once they arrive. because it is a connectionless service, it does not create virtual circuit.

HTTP Message Format


The HTTP specifications ([RFC 1945] and [RFC 2068]) define the HTTP message formats. There are two types of HTTP messages, request messages and response messages, both of which are discussed below.

HTTP Request Message


Below is a typical HTTP request message: GET /somedir/page.html HTTP/1.1 Connection: close

User-agent: Mozilla/4.0 Accept: text/html, image/gif, image/jpeg Accept-language:fr (extra carriage return, line feed) The message is written in ordinary ASCII text, so that our ordinary computer-literate human being can read it. Second, the message consists of five lines, each followed by a carriage return and a line feed. The last line is followed by an additional carriage return and line feed. Although this particular request message has five lines, a request message can have many more lines or as little as one line. The first line of a HTTP request message is called the request line; the subsequent lines are called the header lines. The request line has three fields: the method field, the URL field, and the HTTP version field. The method field can take on several different values, including GET, POST, and HEAD. The great majority of HTTP request messages use the GET method. The GET method is used when the browser requests an object, with the object identified in the URL field. In this example, the browser is requesting the object /somedir/page.html. (The browser doesn't have to specify the host name in the URL field since the TCP connection is already connected to the server.) The version is self-explanatory; in this example, the browser implements version HTTP/1.1. At the header lines in the example by including the Connection: close header line, the browser is telling the server that it doesn't want to use persistent connections; it wants the server to close the connection after sending the requested object. Thus the browser that generated this request message implements HTTP/1.1 but it doesn't want to bother with persistent connections. The User-agent: header line announces to the server the user agent, i.e., the browser type that is making the request. Here the user agent is Mozilla/4.0, a Netscape browser. This header line is useful because the server can actually send different versions of the same

object to different types of user agents. (Each of the versions is addressed by the same URL.) The Accept: header line tells the server the type of objects the browser is prepared to accept. In this case, the client is prepared to accept HTML text, a GIF image or a JPEG image. If the file /somedir/page.html contains a Java applet , then the server shouldn't send the file. Finally, the Accept-language: header indicates that the user prefers to receive a French version of the object, if such an object exists on the server; otherwise, the server should send its default version.

Here is a look at the general format for a request message, as shown in Figure:

Figure : general format of a request message


The general format follows closely the example request message above. It could be noticed, however, that after the header lines there is an "Entity Body". The Entity Body is not used with the GET method, but is used with the POST method. The HTTP client uses the POST method when the user fills out a form -- for example, when a user gives search words to a search engine such as Yahoo. With a POST message, the user is still requesting a Web page from the server, but the specific contents of the Web page depend on what the user wrote in the form fields. If the value of the method field is POST, then the entity body contains what the user typed into the form fields. The HEAD method is similar to the POST method. When a server receives a request with the HEAD method, it responds with an HTTP message but it leaves out the requested object. The HEAD method is often used by HTTP server developers for debugging.

Types of HTTP request:

There are two types of HTTP request: simple requests, and full requests. A simple request is a command to get a URI. For example: GET http://info.cern.ch/<CR><LF> where <CR> is a carriage return character; <LF> is a line feed character. The server's response is to send the object specified by the GET request back to the client via the socket. In the case of a simple request, the object is simply sent back to the browser. In the event of a full request, the object is encapsulated using the MIME protocol, and a descriptive header precedes it on its way to the client. MIME is the internet standard for multi-media electronic mail, and it is described in the internet standards documents RFC1521 and RFC1522 (formerly RFCs 1341 and 1342). Because a lot of mail gateways and network connections cannot handle full 8-bit binary data, or even 8-bit text, or long lines of text, MIME "encapsulates" files for transport; a MIME message consists of a header (specifying the encoding method used) and an encoded form of the file, that is intended to pass through any mail gateway, however primitive. For example, a valid MIME content-type might be: Application/postscript Indicating that the file in question contains applicationspecific information, of type postscript. Use of the MIME protocol gives HTTP two advantages. Firstly, it can send ASCII-only connections, and handle data passed through email gateways. Secondly, it serves to identify

the type of data in the transmission. HTTP is not restricted to sending HTML; the MIME header identifies the method that must be used to unpack the document, and the format of the document. A full request is somewhat more complex. It is a text message from the client, encoded in accordance with RFC-822 (originally used to define the header of email messages). It has this form: Method URI Protocol Version <CR><LF>

[*<HTRQ Header>]

[<CR><LF> <data>] "Method" is actually a command to the server. GET is a method; there are others, and we'll see them shortly. "URI" is short for Universal Resource Indicator. At present, this is just a URL; however, the URI specification subsumes URLs and other, as yet unused, types of resource. "Protocol Version" is usually a fixed piece of text that indicates the version of the protocol in use. At present it is "HTTP/1.0", but this allows for change when HTTP 1.1 and HTTP-NG become available. Here is an example full request: METHOD GET http://info.cern.ch/ HTTP/1.0<CR><LF>

The "METHOD GET" part of the request indicates that it is a GET request, as opposed to a POST or PUT or some other type. The "HTTP/1.0" following the URI indicates that the request uses the HTTP 1.0 protocol. The HTRQ Header is an optional element or elements, separated by <CR><LF> pairs. They are encoded in RFC-822 format, so that each line consists of a keyword, followed by a colon, then a value or values. They are used to transmit control information about the transaction (such as who it originates from, what types of MIME-encoded data the client can accept, how they should be encoded, and what language version to send if the document specified by the GET command is available in multiple versions in different languages.) The "Data" portion is optional. Again, it consists of a MIME-encoded message. It is determined by the earlier information in the request; for example, a PUT command (which uploads a URL to a server) supplies the file to upload in the data portion of the request.

HTTP Response Message


Here is a typical HTTP response message. This response message could be the response to the example request message just discussed. HTTP/1.1 200 OK Connection: close Date: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 09:23:24 GMT Content-Length: 6821 Content-Type: text/html

data data data... The response message has three sections: an initial status line, six header lines, and then the entity body. The entity body is the meat of the message -- it contains the requested object itself (represented by data data data ...). The status line has three fields: the protocol version field, a status code, and a corresponding status message. In this example, the status line indicates that the server is using HTTP/1.1 and that that everything is OK (i.e., the server has found and is sending the requested object). At the header lines the server uses the Connection: close header line to tell the client that it is going to close the TCP connection after sending the message. The Date: header line indicates the time and date when the HTTP response was created and sent by the server. Note that this is not the time when the object was created or last modified; it is the time when the server retrieves the object from its file system, inserts the object in response message and sends the response message. The Server: header line indicates that the message was generated by an Apache Web server; it is analogous to the Useragent: header line in the HTTP request message. The Last-Modified: header line indicates the time and date when the object was created or last modified. The Last-Modified: header is critical for object caching, both in the local client and in network cache (a.k.a. proxy) servers. The Content-Length: header line indicates the number of bytes in the object being sent. The Content-Type: header line indicates that the object in the entity body is HTML text. (The object type is officially

indicated by the Contenet-Type: header and not by the file extension.) Note that if the server receives an HTTP/1.0 request, it will not use persistent connections, even if it is an HTTP/1.1 server. Instead the HTTP/1.1 server will close the TCP connection after sending the object. This is necessary because an HTTP/1.0 client expects the server to close the connection.

Figure : General format of a response message


Here is the general format of a response message, which is shown in Figure . The status code and associated phrase indicate the result of the request. Some example status codes and associated phrases include:

200 OK: Request succeeded and the information is returned in the response.

301 Moved Permanently: Requested object has been permanently moved; new URL is specified in Location: header of the response message. The client software will automatically retrieve the new URL. 400 Bad Request: A generic error code indicating that the request could not be understood by the server. 404 Not Found: The requested document does not exist 505 HTTP Version Not Supported: The request HTTP protocol version is not supported by the server.

HTTP Methods
The Method field in HTTP indicates the method to be performed on the object identified by the URL. The method GET below is always supported, The list of other methods acceptable by the object are returned in response to either of these two requests. This list may be extended from time to time by a process of registration with the design authority. Method names are case sensitive. The set of common methods for HTTP/1.1 is defined below. Although this set can be expanded, additional methods cannot be assumed to share the same semantics for separately extended clients and servers.

Safe and Idempotent Methods Safe Methods


Implementers should be aware that the software represents the user in their interactions over the Internet, and should be careful to allow the user to be aware of any actions they might take which may have an unexpected significance to themselves or others.

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe". This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested. Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.

Idempotent Methods
Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are inherently idempotent. However, it is possible that a sequence of several requests is non- idempotent, even if all of the methods executed in that sequence are idempotent. (A sequence is idempotent if a single execution of the entire sequence always yields a result that is not changed by a reexecution of all, or part, of that sequence.) For example, a sequence is non-idempotent if its result depends on a value that is later modified in the same sequence. A sequence that never has side effects is idempotent, by definition (provided that no concurrent operations are being executed on the same set of resources).

OPTIONS

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating resource retrieval. Responses to this method are not cacheable. If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body. If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof). If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource. A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY

be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0". The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a MaxForwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the MaxForwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.

GET
The GET method means retrieves whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, IfUnmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.

The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client. The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13.

HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The Meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining Meta information about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

POST
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST

is designed to allow a uniform method to cover the following functions: - Annotation of existing resources; - Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; - Providing a block of data, such as the result of submitting a form, to a data-handling process; - Extending a database through an append operation. The actual function performed by the POST method is determined by the server and is usually dependent on the RequestURI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database. The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result. If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields. However, the 303 response can be used to direct the user agent to retrieve a cacheable resource.

PUT

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) responses. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases. If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable. The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

It MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request. A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying "the current version" which is separate from the URI identifying each particular version. In this case, a PUT request on a general URI might result in several other URIs being defined by the origin server. HTTP/1.1 does not define how a PUT method affects the state of an origin server.

DELETE
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location. A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity. If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

TRACE
The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request. A TRACE request MUST NOT include an entity. TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information. The value of the via header field is of particular interest, since it acts as a trace of the request chain. Use of the Max-Forwards header field allows the client to limit the length of the request chain, which is useful for testing a chain of proxies forwarding messages in an infinite loop. If the request is valid, the response SHOULD contain the entire request message in the entity-body, with a Content-Type of "message/http". Responses to this method MUST NOT be cached.

UNLINK
This method deletes metainformation about an object. The request contains object geaders which are to be removed. Only headers exactly matching the headers given are removed. Obviously the operation may be used for unlinking objects. It may also be used for removing other metainformation such as object title, expiry date, etc.

LINK

The link method of HTTP adds meta information (Object header information) to an object, without touching the object's content. For example, it requests the creation of a link from the specified object to another object. The request is followed by a set of object headers which are to be added. In cases in which a new header is added and the semantics of the header do not allow it to coexist with a similar header, then the previous header is deleted. For example, an object may only have one title, so specifying a title overwrites and preexisting title. LINK is like POST except that

no storage is requested for the destination object, and The destination is not assumed to be subordinate to the specified object.

Proxy Server
A server that sits between a client application, such as a Web browser, and a real server. It intercepts all requests to the real server to see if it can fulfill the requests itself. If not, it forwards the request to the real server. A Web proxy server is a specialized HTTP server. The primary use of a proxy server is to allow internal clients access to the Internet from behind a firewall. Anyone behind a firewall can now have full Web access past the firewall host with minimum effort and without compromising security. The proxy server listens for requests from clients within the firewall and forwards these requests to remote internet servers outside the firewall. The proxy server reads responses from the external servers and then sends them to internal client clients. In the usual case, all the clients within a given subnet use the same proxy server. This makes it possible for the proxy to cache

documents efficiently that are requested by a number of clients. People using a proxy server should feel as if they are getting responses directly from web servers. Most proxy servers are implemented on a per-access method basis. Proxy servers can allow or deny internet requests according to the protocol of the requests. For instance a proxy server can allow calls to FTP servers while denying calls to HTTP servers.

Figure 26 A Normal Web Transactions

Figure 27 An HTTP Transaction via a Proxy Server Proxy servers have two main purposes:

Improve Performance: Proxy servers can dramatically improve performance for groups of users. This is because it saves the results of all requests for a certain amount of time.

Consider the case where both user X and user Y access the World Wide Web through a proxy server. First user X requests a certain Web page, which we'll call Page 1. Sometime later, user Y requests the same page. Instead of forwarding the request to the Web server where Page 1 resides, which can be a time-consuming operation, the proxy server simply returns the Page 1 that it already fetched for user X. Since the proxy server is often on the same network as the user, this is a much faster operation. Real proxy servers support hundreds or thousands of users. The major online services such as CompuServe and America Online, for example, employ an array of proxy servers.

Filter Requests: Proxy servers can also be used to filter requests. For example, a company might use a proxy server to prevent its employees from accessing a specific set of Web sites.

When Web Proxy Servers are Useful


We can use a proxy server in a number of ways, including:

Permitting and restricting client access to the Internet based on the client IP address Caching documents for internal documents Selectively controlling access to the Internet and subnets based on the submitted URL Providing Internet access for companies using private networks Converting data to HTML format so it is readable by a browser

Caching Documents
Usually, the clients within a subnet access the same Web proxy server. Some proxy servers let you cache internet documents for clients within the local area network. Caching documents means keeping a local copy of internet documents, so that the server doesnt need to request them over and over again. Caching is more effective on the proxy server than on each client system. This saves disk space because only a single copy is cached. Caching on the proxy server means more documents that are often referenced by multiple browsers can be cached more efficiently. The system administrator can predict which documents are worth caching for a long time and which are not. Caching also makes it possible to browse the Web even if a Web server, or even the external network, is down, as long as one can connect to the proxy server. This improves service to remote network resources, such as busy FTP sites and transient Gopher servers that are often unavailable remotely, but may be cached locally.

Communication via a Proxy Server


The proxy server acts as both a server system and a client system. It is a server when accepting HTTP requests from browsers, and acts as a client system when its browser software connects to remote servers to retrieve documents. The proxy server uses the header fields passed to it by the browser without modification when it connects to the remote server. This means the browser does not lose any functionality when going through a proxy. A complete proxy server should be able to communicate all the Web protocols, the most important ones being HTTP, FTP,

Gopher, and WAIS. Proxies that handle only a single Internet protocol, such as HTTP, are possible, but a Web browser would then require access to other proxy servers to handle the remaining protocols. When a browser sends a request through a proxy server, the browser always uses HTTP for the transactions with the proxy server. This is true even when the user wants to access a remote server that uses another protocol; for example, FTP. Instead of specifying only the pathname and search keywords to the proxy server, the browser specifies the full URL. This way the proxy server has all the information necessary to make the actual request to the remote server specified in the request URL, using the protocol specified in the URL.

HTTP Browser Request to Remote HTTP Transaction


When you use a proxy server as a client system, it acts as a browser to receive documents. The following is a typical example of a proxied HTTP request: When you enter a full URL, for example:
http://example.com/information/ProxyDetails.html

The browser converts the URL to:


GET http://example.com/information/ProxyDetails.html

The browser then connects to the server, and then the proxy server provides the connection to the Internet.

The proxy server converts this request to:

GET /information/ProxyDetails.html

The proxy server connects to the server running on mycompany.com. The server then issues the command and waits for a response, returns the response to the proxy server, which then returns the response to the client. Figure shows a browser making a request to the proxy server using HTTP and specifying a full URL. The figure shows that the URL passed between the proxy server and the remote server specifies neither the remote host name nor the HTTP protocol.

Figure :An HTTP Transaction via a Proxy Server MIME


MIME stands for Multipurpose Internet Mail Extensions. The purpose of MIME is to allow the use of a wide variety of media types through internet mail. The Internet Engineering Task Force (IETF) Working Group defined the standard for MIME in 1992.

Internet mail could originally only transfer seven bit ASCII messages. MIME allows the sending of text and many other file formats including formats for images, sound, video and more. It also allows the sending of messages in more than just US-ASC text along with the capability to put multiple objects in one message, and use more than one font in a message. One of the reasons that MIME is so important today is that its standard is being used to identify content for sources other than mail including HTML file content and more. MIME competes with the X.400 Message Handling Standard. MIME allows messages with several parts which may be of different types to be sent. A "body of information" refers to a part of a multipart message.

MIME Functionality
MIME provides for identifying the methods used to both transfer and process the information being sent. In some cases, the data being transmitted cannot be sent in its original form over various transport mechanisms. Some of this data must be transformed into a seven bit format, then restored to the original format when it is received. MIME provides:

Specification of how the content is encoded for transfer (Content-Transfer-Encoding). The type of content which will help identify programs that must be used to present the content to the user.

MIME Header Fields


MIME defines a number of new RFC 822 header fields that are used to describe the content of a MIME entity. These header fields occur in at least two contexts: 1. In a MIME body part headers within a multipart construct. 2. As part of a regular RFC 822 message header. The formal definition of these header fields is as follows:
entity-headers:= [content CRLF] [encoding CRLF] [id CRLF] [description CRLF] *(MIME-extension-field CRLF) MIME-message-headers:= entity-headers fields version CRLF

The ordering of the header fields implied by this BNF definition should be ignored.
MIME-part-headers: = entity-headers [fields]

Any field not beginning with "content-" can have no defined meaning and may be ignored. The ordering of the header fields implied by this BNF definition should be ignored.

Objective
In developing this architecture, the following were the objectives considered in order to ensure practicality of implementation: The architecture should be straightforward to implement and administer and be freely exportable. To allow reliable service of web page over network when the request for web page is made. Web server is responsible for the enforcement of security within his own domain, allowing him to use the most appropriate level of security for their user base. The authenticated connection approach should be implemented to make it more difficult for anonymous SPAM to enter the system. The authentication mechanism should be lightweight and authentication needs to occur only at the time configuration of web server is changed. The system should be self-managed. The security scheme should account for a basic level of security but be easily extensible so that some services may implement a higher degree of security. It is obviously very important that server implementing this architecture be able to handle large numbers of users and requests across the protocol. Each operation should be self-contained i.e. fully encapsulating a given request in a single protocol request with a single protocol response.

Challenges faced

1. Building the Server framework code. The Server use TCP sockets to communicate and a MESSAGE java object is passed across the server-clients. 2. Building the SWING component.

Requirements and Analysis


Basic Requirements
The goal is to design a system that would be flexible, yet practical to implement. The primary requirement is to design a system that should: Be platform independent Web server should be platform independent. Platform independent means that web server should support Windows as well as UNIX. As most of the servers are designed for specific platform as IIS is developed for windows. Similarly Apache support over UNIX. Be robust enough to handle huge load The system should be well designed to handle a large amount of request. It should not give any problems if the load increases. As the web servers main function is to respond client request over network. Load of request is not constant at a time so web server must be designed in such a way that it does not give any problem on increasing load. Be user Friendly Web server should be user friendly. The user interfaces designed should be interactive and support users requirement. Be capable over network

Web server should be capable over network which could be either local network or Internet. It must support the protocols of network which are followed during transmission over network. Support protocols over Internet and Local network Web server should follow the protocols of network. It means that web server should support TCP/IP and HTTP protocols. Some other protocols which are important during transmission are SMTP, UDP etc. Output should be generated in standard format Response generated by the web server corresponding to a request must follow the format which includes mime header and the body .so that the response generated from web server does not concentrate over a particular browser. For example response generated in reply of request sent by internet explorer is different from request sent by Netscape navigator. Support caching of web page Web server should support caching of web pages. as the request for same web page is made in a bulk amount so it is very time consuming and performance degradable task to process the same request every time .this reduces the efficiency of web server. So web server need to support the concept of proxy server. Be scalable to hundreds of users. The system should be easily available and installable. The users should not find any problem in using the system. It should incorporate good user-friendly interface and easy to use services/features. This will attract more and more people to register to the software and use its services.

Initially support at least these main end-user features:


The system should be designed such that it supports at least the following basic functionality initially: Registration and Authentication Only one user should be able to register to the system if he wants to access web server. This will require a username and password for registration. The system should prompt the user for these details and store it in the database. Now, the user has to enter the correct username and password to login to the system. If user enters wrong username or password, the window does not disappear and the fields get blank. This is how authentication will be achieved. There should a feature in the system to allow a user to change his password at any time. In that case user should be prompted for new username, new password. Configuration Web server should have a user interface through which user can make changes in the configuration setting. It provides flexibility to end user about placing his directory any where in the auxiliary storage. in the configuration setting user has the options to change the path and the port no. through which web server listens to the request and generate response. Be extensible The code design should always be extensible, so new features can be added incrementally without requiring redesign and while allowing for backward compatibility. And additions or enhancements should never require redesign or any changes in the

previous implementation. Otherwise it is considered to be the major flaw in the design. Any software should be designed keeping in mind that the new features would just be added to the system without re-engineering or redesign.

What languages should be used? Java, C, C++, etc.


After having thought of the basic steps in designing the system, the next step would be to decide the language/platform in which the software will be developed. This is one of the major decisions to be made since it will entirely depend upon the requirement of the project. There are various languages available in which the system can be designed. But a particular language has to select keeping in mind the exact requirement i.e. whether you need to incorporate procedural approach or object-oriented approach in your code, whether the software developed will be platform dependent or independent, etc. So all the pros and cons have to be considered properly. Keeping in mind our main goal to develop a platform independent solution Java will be most suitable language for development.

What standards/protocols should be used?


For the proper communication between clients and server there should be a standard set of rules or language (protocol) to be followed by both. Protocol should cover all the proposed features that need to be incorporated in the system and this protocol should be extensible enough to incorporate future enhancements. System should be designed keeping this very important criterion in mind.

Why Java?

The complete system has been developed using Java programming language. Java is an innovative programming language that has become the language of choice for programs that need to run on different computer systems. The most common Java programs are applications and applets. Applications are standalone programs while Applets don't run standalone. Instead, applets adhere to a set of conventions that lets them run within a Java-compatible browser. Being able to embed executable code in a Web page introduces a vast range of exciting possibilities. Instead of being a passive presentation of text and graphics, a Web page can be interactive in any way that we want. We can include animations, games, interactive transaction processing- the possibilities are almost unlimited. Java also provides other programming capabilities like threads, socket and User Interface development.

Characteristics
Some important characteristics of Java, which are relevant to this project, are listed below: Portability Perhaps the most important characteristics of Java is that it was designed to be machine independent. Java programs can run unchanged on any computer that supports Java. An interactive application written in Java will only require a single set of sources code, regardless of the number of different computer platforms on which it is run. Java Virtual Machine We can run Java programs on a wide variety of computers using a range of operating systems. Our Java programs will run as well as on a PC running Windows 95/98/ME/NT/2000 as it will on Linux or a Sun Solaris workstation or even on Macintosh systems. This is

possible because a Java program does not execute directly on your computer. It runs on a standardized hypothetical computer that is called the Java virtual machine or JVM, which is emulated inside our computer by a program. A Java compiler converts the Java source code that we write into a binary program consisting of byte codes. Byte codes are machine instructions for the Java virtual machine. When we execute a Java program, a program called the Java interpreter inspects and deciphers the byte codes for it, checks it out to ensure that it has not been tampered with and is safe to execute. It then executes the actions that the byte codes specify within the Java virtual machine. A Java interpreter can run stand-alone, or it can be part of a web browser such as Netscape Navigator or Microsoft Internet explorer where it can be invoked automatically to run applets in a Web pages. Because our Java program consists of byte codes rather that native machine instructions, it is completely insulated from the particular hardware on which it is run. Any computer that has the Java environment implemented will handle our programs as well as any other, and because the Java interpreter comes between our program and the physical machine, it can prevent unauthorized actions in the program being executed. Object Oriented A software design method that models the characteristics of abstract or real objects using classes and objects. The next most important characteristic of Java is that it is object oriented. The object-oriented approach to programming is also an implicit feature of all Java programs. Not only is Java object oriented, but it also manages to avoid many of the difficulties and complications that are inherent in some other object-oriented languages, making it very straightforward and easy to learn.

Concepts:

Encapsulation - Encapsulation is an attribute of OOP languages that allows the data to be hidden behind a set of interface procedures or protocol. This ensures that the programmer needs no nothing about the underlying data structure or content, they simply access the data via a set of defined interfaces. Inheritance - In an OOP language, a class can be derived from one or more classes. That is to say, the class not only contains the attributes and methods specific to it, it also picks up (or inherits) the attributes and methods of the class or classes from which it was derived Polymorphism - Polymorphism is the application of the same operation to different types of entity. Polymorphism can be considered as a unique feature of OOP allowing different objects to respond to the same message in there own specific way. Reusability - The benefit of reusability comes as a result of the previous 3 features. The attributes of Polymorphism, Inheritance and Encapsulation facilitate the reuse of code and the establishment of class libraries. Because the data is hidden and because the methods can be altered or overridden it is possible to use methods developed to satisfy one application in a completely different environment.

Comparison between Modular and Object Oriented Programming


Modular Programming With modular programming, procedures of a common functionality are grouped together into separate modules. A program therefore no longer consists of only one single part. It is now

divided into several smaller parts which interact through procedure calls and which form the whole program. The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters. Each module can have its own data. This allows each module to manage an internal state, which is modified by calls to procedures of this module. However, there is only one state per module and each module exists at most once in the whole program. Modular Programming Problems: Explicit Creation and Destruction Decoupled Data and Operations Missing Type Safety The problem here with modular programming is, that you must explicitly create and destroy your list handles. Then you use the procedures of the module to modify each of your handles.

Modular programming technique


In contrast to that, in object-oriented programming we would have as many list objects as needed. Instead of calling a procedure that we must provide with the correct list handle, we would directly send a message to the list object in question. Roughly speaking, each

object implements its own module allowing for example many lists to coexist. Each object is responsible to initialize and destroy itself correctly. Consequently, there is no longer the need to explicitly call a creation or termination procedure.

Java Features Used


Swing for User Interface Swing is the next-generation GUI toolkit that Sun Microsystems has developed for the Java language. It is essentially a vast component framework built over parts of the older AWT component libraries used in Java 1.0 and 1.1. Swing is written in 100% Java; there are no native calls. Hence, it can run on any platform with a compatible Java virtual machine. The Swing package is part of the JavaTM Foundation Classes (JFC) in the Java platform. The JFC encompasses a group of features to help people build GUIs; Swing provides all the components from buttons to split panes and tables. It gives developers a chance to create a powerful, portable application that can not only target users on any Java-compatible platform, but also target their desired lookand-feel as well. Swing is only one part of the JFC. The Java Foundation Classes (JFC) are a collection of packages that developers can use to create full- featured applications in Java. They include AWT, Swing, Accessibility, Java 2D, and Drag and Drop functionality. Swing employs a component design known as model-viewcontroller (MVC), which allows you to abstract out the data of a component (model) from how it is displayed on the screen (view). This is a wonderful design from a programming perspective because its tried-and-true and molds into Java nicely. With Swing, there is a slight modification: the view and the controller are fused into a single object called the "UI-delegate," which manages the visual

aspect of the component. Programmers can either use the Swing components as they are, or modify parts of the model or delegate to greater deal with their needs. Threads A thread--sometimes called an execution context or a lightweight process--is a single sequential flow of control within a program. You use threads to isolate tasks. Each thread is a sequential flow of control within the same program. Each operation associated with a thread runs independently from the others, but at the same time. A single thread also has a beginning, a sequence, and an end and at any given time during the runtime of the thread, there is a single point of execution. However, a thread itself is not a program; it cannot run on its own. Rather, it runs within a program. The following figure shows this relationship.

Multithreaded applications deliver their potent power by running many threads concurrently within a single program. From a logical point of view, multithreading means multiple lines of a single program can be executed at the same time, however, it is not the same as starting a program twice and saying that there are multiple lines of a program being executed at the same time. In this case, the operating system is treating the programs as two separate and distinct processes. Multithreaded applications deliver their potent power by running many threads concurrently within a single

program. From a logical point of view, multithreading means multiple lines of a single program can be executed at the same time, however, it is not the same as starting a program twice and saying that there are multiple lines of a program being executed at the same time. In this case, the operating system is treating the programs as two separate and distinct processes.

Java has two ways of creating threads: implementing an interface and extending a class. Extending a class is the way Java inherits methods and variables from a parent class. In this case, one can only extend or inherit from a single parent class. This limitation within Java can be overcome by implementing interfaces, which is the most common way to create threads. Using threads in Java will enable greater flexibility to programmers looking for that extra edge in their programs. The simplicity of creating, configuring and running threads lets Java programmers devise portable and powerful applets/applications that cannot be made in other third-generation languages. Threads allow any program to perform multiple tasks at once. In an Internet-aware language such as Java, this is a very important tool. Networking Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:

In the Java programs that communicate over the network, programming is done at the application layer. Typically, a developer doesn't need to concern with the TCP and UDP layers. Java classes provide system-independent network communication. TCP TCP (Transmission Control Protocol) is a connectionbased protocol that provides a reliable flow of data between two computers. When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection. This is analogous to making a telephone call. TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported. TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. UDP UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.

The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called datagrams, from one application to another. Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other. Ports Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application. In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server's port, as illustrated here:

In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure:

Sockets A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Socket classes are used to represent the connection between a client program and a server program. Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. To make a connection request, the client tries to rendezvous with the server on the server's machine and port.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. Note that the socket on the client side is not bound to the port number used to rendezvous with the server. Rather, the client is assigned a port number local to the machine on which the client is running.

Hardware and Software Requirements


The following section describes the hardware and the software requirements for this project. Hardware Requirements Pentium based PC Windows or UNIX based machines 128 MB RAM

Software Requirements JDK1.3 or higher MS Office for documentation Adobe Photoshop 5.5 Windows/WinNT(to run server)

Functional Requirement
Functional requirement are end user information requirement that are not tied to the hardware, software, network, data, and people resources that end user presently use or might use in the new system.

User Interface Requirement


User interface requirement analysis deals with the study of end user requirement .it involves the analysis of user interfaces required to fulfil the requirement of user .in the web server user basically these user interfaces which are: An interface to inform the user about his configuration setting which involve the directory path, port number through which server listens the request, local host IP address, network IP address etc. It act as the main window of web server through which we make move towards each interface and can have control over the server .control over server means we can stop the server, we can run the server, we can exit from the server etc. An interface is desired for authentication purpose through which user proves his identity before changing the configuration of server and password etc. An interface is required to provide an option to user to change the configuration of web server according to his system settings. it should involve an option to change the path of root directory where web pages are stored .it should also have an option to change the port no. it should have an option for change password setting .

An interface is required to change the password and username. As the web server supports only one user at a time to avoid conflict so .it should have options for change in username as well as password. It should also have an option to cancel the event to reject the changes made currently. An interface is needed to show the server status. Server status refers the fact that how much request are fulfilled, how many bytes of information is produced etc. An interface is required to help the user about server. it should provide guidelines to user about web server. An interface is required to provide information about developer to user. Processing Requirement Processing requirement deals with the analysis of process performed in the web server .on the basis of analysis we have identified certain process which are necessary in the web server. These are as follows: We need a process which initialize the web server by loading the configuration file and initialize a server socket of max queue 50 and bind this server socket to a port no and starts listening for the request. We need a process which handles request by getting the request structure and also identifies the request made for him. We need a process which identifies the type of request and deliever the request according to requirement We need a method which handles HTTP GET method .

We need a process which keeps the pages in cache which are served once in the web server so that web server should be made efficient. We need a method through which we identify the parameters of request and the web page requested by the client.we also need a method which reads file from the local disk. We also need a process which checks the page whether it is page is present in the cache or not. We also need a method for handling erroneous request so that if any web page which is requested is not present is handled by it. We need a process through which we can report server on each hit made by the server. It also respond to server about the bytes transferred during response generation. We need a method which creates the mime header format for the response generated for the request appeared .mime is the protocol which is used in the messaging over the internet. We need a method which writes the mime header along with the body of the file as the response to the client request in the local disk by the name of URL and sent the content of the response to the client socket. Above mentioned processes are some of the basic methods which need to be followed in processing a request. except this certain other processes which are identified at the user end are as follows: For authentication purpose we need a process through which we compare the username and password with the registered user so that only correct person goes for change in the configuration of server.

For change in the configuration purpose we need a process through which we can change the configuration according to our need. At the user end we need to show the status of server i.e. how much request it fulfill, how much bytes of data is transferred etc. so we need a process which retrieves the data and show the status to the user. At the user end we need a process through which we can control the functionality of the server i.e. stop the server or run the server. We also need a process through which we can change the username and password.

Storage Requirement
Storage requirement deals with the storage management of the software and related file system so that fast retrieval and updating is made possible. In the web server we need auxiliary storage for keeping our file system where web pages are stored and all other data records related to web server are stored. Along with this we need a local storage so that web pages which are widely requested are kept in that storage so that their retrieval is made easy and efficient. As in the process requirement we have identified the requirement of cache to store web page temporarily so if they are stored in the auxiliary storage it degrades the performance of web server.

System Modeling
The analysis model must achieve three objectives: To describe what the end user require To establish a basis for the creation of software design To define a set of requirement that can be validated once the software is built. To accomplish these objectives the analysis model are derived during analysis. In the analysis model we deal with data modeling, functional modeling and behavioral modeling. Data modeling basically answers a set of specific question that are relevant to any data processing application. These may include as what are primary data object to be processed by the system, what is the composition of each data object and what attribute describe the data object etc.. To answer these questions we make use of entity relation diagram, which focuses solely on data, representing a data network that exists for a system. Function model is the representation of information flow in the software via functions. Functional model begins with a single context level model. Over a series of iterations more and more functional details is provided until a thorough delineation of all system is functionally is represented. Data flow diagram is a graphical representation that depicts information flow and transforms that are applied as data move from input to output. It may be used to represent any level of abstraction of a system.

Function Modeling
Software transforms information and in order to accomplish this it must perform at least three generic functions: input, processing and output. When functional model of an application are

created the software engineer focuses on problem specific functions. The functional model begins with a single context level model (i.e. the name of the software to be built). Over a series of iteration more and more functional details is provided , until a thorough delineation of all system functionally is represented.

Notation used in data flow diagram

The data flow diagrams for web server are as follows:


Context Level Dfd:

hits record request from client web server software initialising record access record

response toclient hits by cache output record

DFD Level 1

initialise data intialise record

initialise web server

create server socket

portno.
close socket process the client request bind socket with port

socket
create TCP/IP hits record socket for output record request access record response to client

request from client

DFD Level 2

error

url

get filenam e

file n a m e url read file m im e type filelength url inputstream get m im e header

m im eheader

l oa d file in to c a c h e

outputstream

uce

generate HT TP response

write request in outputstream

response to client

Behavioral Modeling

State Transition Diagram Notation used in the state transition diagram

State transition diagram (STD) indicates how the system behaves as a consequence of external events. To accomplish this, the STD represents the various modes of behavior (called states) of the system and the manner in which transition are made from state to state. The STD serves as the basis for behavioral modeling.

run web server

go for menu item stop clicked


web server stopped

run clicked server runs

main window go for menu item of web server appear

configuration clicked thread suspend

server status clicked thread suspend server status window appear

web server stopped

web server initialises

load authentication window

wait for request

lick ok/correct us ername,pa s s word window disappear

get the request click ok/cancel configuration change calculate parameters of request click cancel window disappear read the file

load cofiguration window pa s s word cha nge clicked window dis a ppea r configuration window disappear

password change window appear click ok/cancel change occur window disappear

load file in cache

generate mime header for response

generate respose

System Design
System analysis describes what a system should do to meet the information needs of user while system design specifies how the system will accomplish this task. System design consist of design activities that produce system specification satisfying the functional requirement that were developed in the system analysis process.

User Interface Design

The user interface design activity focus on supporting the interaction between and user and their computer based applications. Designers concentrate on the design of attractive and efficient forms of user input and output such as easy to use Internet or intranet web pages. In the web server we have designed certain user interfaces to meet the requirements identified in the analysis phase. as for the development of web server we chose java as our programming language which provide graphical tools in the form of abstract window toolkit and applet. It also provides swing package to develop user interfaces which are very helpful in developing following user interfaces. On the basis of analysis phase requirement we designed several user interfaces which are as follows:

Web Server main window

This window is the first appeared window of web server. This window is the main window of the web server through which we can control our web server and also we can move to different windows just by clicking at the menu items appeared over this window.

Server Status Window

Server Status window is the second user interface designed for the web server. The purpose behind designing this window is to show the server statistics to the end user that how much request are fulfilled by the web server.

Authentication

Authentication window is another window which appears when user wants o change the configuration of the server or wants to change the username and password.

Configuration

Configuration window is designed to fulfill the requirement of configuration change in the web server.

Change Password

In the Change Password window we tried authorize user to provide the option to change the username and password.

Output Design
Output design deals with designing of the response generated by the server. For the basic request the output should be according to protocols of the Internet. So the output should have mime header followed by the body (content) of the requested page in html form: General format of the web server output is as follows: HTTP/1.0 statuscode reason Mime haeder Data(Content of the file) The format of mime header is like this: dd mm yyyy hh:mm:ss zzz Server name:. Content type:.. Content-length:. The data part of the output has the simple HTML codes whose general format is like this: <html> <head>.</head> <body> . </body> </html>

Coding
Coding phase of software development deals with the development of codes in any programming language to implement the design phase which is the previous phase. In the web server we coded five classes to implement the functionality of web server through which the requests are handled and proper response is generated. To implement the user interface we develop seven classes. These seven classes gives rise to interfaces through which user interact with the server and controls its functionality. Here is brief view all the classes and their functions which are coded in java as we have chosen java as the programming language for coding. Class: Server Thread ServerThread class is designed to implement the multithreading in the web server. Whenever server initializes itself a new thread is created which load the server properties and initializes the server. This class also handles the function of stopping the server by stopping thread. This class implements Runnable to implement thread. The brief descriptions of the functions of ServerThread class are as follows:
Function ServerThread ( ) What it do? ServerThread ( ) is the constructor for ServerThread class which does not require any parameter for the initialize the class. start ( ) method is used to create the thread.

start ( )

stop ( ) run ( )

stop ( ) method is used to stop the thread. run ( ) method is called to start the thread. This function calls the Server class to initialize web server. stop1 ( ) method is called to suspend the local thread for a moment. getport( ) method returns the port no. and path of root directory which it read from a file.

stop1( )

getport( )

Class: Server Server is the main class of web server which initialize the server socket ,handles the request and generate the response. ServerThread class calls the constructor of Server class to start listening process and to load the properties of web server. This class also implements Runnable to implement thread. Server class initialize a thread for each class and handle request by executing thread. But to process the same request so many times degrades the performance of web server so we have provision for caching of pages which are requested earlier to overcome the overhead of full processing of the same request. The functions implemented in the Server class are as follows:
Function Server( ) Server( int, String, LogMessage) What it do Constructor of the class Another constructor for Server class has three parameters: int, String,

LogMessage. It initializes the port to listen on, the directory to retrieve files from, and the interface to send message to. loadprops( ) This method loads the properties of web server from a file. This method is used to start the server. It creates a server thread which initializes a server socket. This method is used to stop the server. This method is called when server thread is started. It creates a new serversocket bind it to a port and goes for listening. When a request comes it creates a socket to handle request and call dorequest ( ) to process request. This method is called to handle request. This method is called per request. It parse the request and mime header and decide to call handeget ( ) or handleproxy ( ) or to invoke error ( ). This method is called when server acts like a simple web server. The parameters to the method tell it where to write the result and which file is needed to read. In this we first check whether the file is present in cache or not. If file is present we respond from there otherwise go for whole processing. readFile ( ) method is called to read

start( ) stop( ) run( )

Dorequest( Socket )

handleget(OutputStream ,String ,mimeheader)

readFile(File ,String )

the targeted file. Actually this function checks for the existence of File. If file is present then it invoke loadFile ( ) otherwise invoke error. loadFile(InputStream, mimeheader ) String, This method is called to read the file and load its content in the cache. It takes three parameters: InputStream, string and mimeheader. A new urlcacheentry is created corresponding to mimeheader information and this urlcacheentry is stored in the cache. This method returns a Boolean value. This method attempt to find a particular file in cache. If file is present then it returns true else false. This method takes an OutputStream and a urlcacheentry. It extracts the information from cache entry to send the response to client. This method is used to hide the conversion of a string to an array of bytes to perform the operation of writing in a bytestream. This method is used to report on each hit to web server in standard format. This method is used to read data from stream until it gets two consecutive new line characters. When it get ,it turns the byte stream into string and return it. This method is used to format an

serverfromcache(OutputStream, String)

writeUce(OutputStream, urlcacheentry)

writeString(OutputStream, String)

logentry(String , String, int, int)

getrawRequest(InputStream)

error(int ,String ,String)

HTML page to send back to web client who make request that cannot be completed. makemimeheader(String ,int) This method is used to create a mimeheader object with some key values filled in it. This method is used to convert the file type in mime format. It takes file name as parameter and returns its mime type in string form. This method converts the string into array of bytes. This method is called when web server act as proxy server on behalf of some server. This method is invoked by dorequest( ) if it get only :// . once these characters are obtained we attempt to fetch the file from the intended host or from the cache of server. This method takes a urlcacheentry object and write it persistently to its local disk.

fnametomimetype(String)

toBytes(String) handleproxy(OutputStream, String, mimeheader)

writeDiscCache(urlcacheentry)

Class: mimeheader MIME (multiple internet mail extension) is an internet standard for communicating multimedia over e-mail system. The HTTP protocol uses and extends the notion of MIME headers to pass general attributes to pass general attributes /value pairs between HTTP client and server. Mimeheader class is designed to handle the problems associated with the mime header. It is subclass of Hashtable so it

can conveniently store and retrieve key/value associated with MIME header. The functions designed in this class are as follows:
Function mimeheader( ) mime header(String) What it do Constructor of the class. Initialize it. Constructor of the class takes a string as parameter format it as mime header and parse it for the initial content of the object. This method is used to take a raw MIME formatted string and enter its key/value pair into a given instance of mimeheader. This method is reverse of parse ( ). It takes key/value pair and return its string representation. This method is used to convert a mime string into canonical form.

parse(String)

toString( )

fix( )

Class: HttpResponse HttpResponse class is class associated with the response from the server. The reply generated from the server must wrap in HTTP format. In this class we append a status code and reason phrase along with the response generated from the server. Status code is an integer and its textual equivalent is stored in reasonphrase. This single line response from HttpResponse is followed by mime header which contains other information about reply.

The function designed in this class are as follows:


Function HttpResponse(String ) What it do Constructor for class .it is used when the HttpResponse is invoked with string argument. Constructor for class. It is invoked when HttpResponse is called with precomputed status code, reasonphrase and mimeheader. This method is used to take the raw data, read from server, parse the status code and reasonphrase and then construct mimeheader out of remaining line. This method is used to get string equivalent of the values of current HttpResponse object.

HttpResponse(int,String, mimeheader)

parse(String)

toString( )

Class: urlcacheentry This class is designed to cache the contents of a document on a server. This class makes an association between the URL and the description of document. The functions associated with this class are as follows:
Function urlcacheentry( String, mimeheader) What it do Constructor for the class.it requires a URL as string and a

mimeheader associated with it. append(byte, int) This method is used to add data to an urlcacheentry object. This method deals with three cases: 1.data buffer is not allocated. 2. Data buffer is too small in comparison to content. 3. data buffer is just fine with content.

Interface: LogMessage LogMessage is a simple interface which is designed to abstract the output of Server. It has only one method.
Function Log( String) What it do This method is used to abstract the output of message from the Server class.

Class: fileread This is the class designed to handle all the file handling functions related to server. This class has following functions:
Function fileread( ) filepaths( ) fileport( ) filehits( ) What it do Constructor for class This function is used to read the path from the file This function is used to read the port no. from file. This method is used to read the no. of hits( no. of request) made by the server This method is used to read the

filecache( )

no. of hits from the cache.

filebytes( )

This method is used to read the no. of bytes sent by the server as output.

Class: filewrite This class is designed to handle all the write operations done by the server in the file. The functions of this class are as follows:
Function filewrite( ) fileport( ) What it do Constructor of the class This method is used to write the port no. in the corresponding file. This methodis used to write the path name in the file This method is used to write the hit data in the file. This method is used to write the hits from cache data in the file. fi lebytes ( ) This method is used to write the output data in the file.

filepath( )

filehits( )

filecache( )

fileaccess( )

This method is used to write access record in the form of log entry in the file.

Class: MainServer This class is designed to create the user interface for the server. This class implements the main window of web server through which we can control the web server. It has following methods:
Function MainServer( ) What it do Constructor for class. It loads the user interface and initializes the web server. This method is used to handle action events performed by the user. This method is used to close the interface by the menu item Exit.

actionPerformed(ActionEvent)

exit( )

Class: Configure This is another class to implement user interface to configure setting by user. It has following functions:
Function Configure( ) act ionPerformed(ActionEvent) What it do Constructor for class. It loads window of configuration. This method is used to handle action events performed by the user.

Class: GettingStart/show/show1

This is another class to implement user interface to provide guidelines to user about server. It has following functions:
Function GettingStart( ) What it do Constructor for class. It loads window of GettingStart. This is invoked from the Mainserver class by clicking menu item.

Show( ) Show1( ) Paint(Graphics)

Constructor for show class. Constructor for show1 class. This method is used to handle graphics display.

Class: Passc This is another class to implement user interface to provide flexibilty to user for change authentication settings. It has following functions:
Function Passd( ) What it do Constructor for class. It loads authentication window. This is invoked when user want to change his configuration.

actionPerformed(ActionEvent)

This method is used to handle action event.

Class: Password/Uname This class is implemented to handle file operations related to username and password.
Function Password( ) passread( ) unamerea d( ) Unam e( ) Passwrite( String) Unamewrite(Str ing) What it do Constructor for Password class This method is used to read password from file. This method is used to read username from file. Constructor for Uname class. This method is used to write password in the file. This method is used to write username in the file.

CODING IN JAVA
import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; class Configure extends JFrame implements ActionListener {

JTextField path,port; String st,p; int por; public Configure(String title) { super(title); Container c=getContentPane(); c.setLayout(new FlowLayout()); c.setBackground(Color.cyan); setSize(280,200); JLabel path1=new JLabel("Path"); c.add(path1); path1.setToolTipText("Enter Path of ur Directory"); path=new JTextField(20); c.add(path); path.addActionListener(this); JLabel port1=new JLabel("port"); c.add(port1); port1.setToolTipText("Enter the port,Default:80"); port=new JTextField(20); c.add(port); port.addActionListener(this); JButton ok,cancel,changepass; ok=new JButton("Ok"); c.add(ok); ok.addActionListener(this); cancel=new JButton("Cancel"); c.add(cancel); cancel.addActionListener(this); changepass=new JButton("Change Password"); c.add(changepass); changepass.addActionListener(this);

setLocation(400,150); setResizable(false); show(); mywindoww aw=new mywindoww(this); addWindowListener(aw); } public void actionPerformed(ActionEvent ae) { MainServer me=new MainServer(); ServerThread h=new ServerThread(); filewrite f=new filewrite(); String str=ae.getActionCommand(); if(str.equals("Ok")) { st=path.getText(); p=port.getText(); por=Integer.parseInt(p); try { f.fileport(por); f.filepath(st); //me.item1.setEnabled(true); //me.item2.setEnabled(false); } catch(Exception e) {} setVisible(false); } else if(str.equals("Cancel")) { setVisible(false); } else if(str.equals("Change Password")) { Passc pa=new Passc("Change Password"); setVisible(false); } } public static void main(String args[])

{ Configure sr=new Configure("hi"); } } class mywindoww extends WindowAdapter { Configure menu; public mywindoww(Configure menu) { this.menu=menu; } public void windowClosing(WindowEvent we) { menu.setVisible(false); } } import java.io.*; class fileread { fileread() { } public int fileport() throws Exception { File f=new File("c:/www/port.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch; String s,p=""; for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } i=Integer.parseInt(p); f1.close(); return i;

} public String filepath() throws Exception { File f=new File("c:/www/path.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch; String s,p=""; for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } f1.close(); return p; } public String filehits() throws Exception { File f=new File("c:/www/hits.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch; String s,p=""; for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } f1.close(); return p; } public String filebytes() throws Exception { File f=new File("c:/www/bytes.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch;

String s,p=""; for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } f1.close(); return p; } public String filecache() throws Exception { File f=new File("c:/www/cache.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch; String s,p=""; for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } f1.close(); return p; } } import java.io.*; class filewrite { filewrite() {} public void fileport(int port) throws Exception { File f=new File("c:/www/port.txt"); FileOutputStream f2=new FileOutputStream(f); String str=Integer.toString(port); byte buf[]=str.getBytes();

f2.write(buf); f2.close(); } public void filepath(String str) throws Exception { File f=new File("c:/www/path.txt"); FileOutputStream f2=new FileOutputStream(f); byte buf1[]=str.getBytes(); f2.write(buf1); f2.close(); } public void fileaccess(String str) throws Exception { File f=new File("c:/www/access.log"); FileOutputStream f2=new FileOutputStream(f); byte buf1[]=str.getBytes(); f2.write(buf1); f2.close(); } public void filehits(int hits) throws Exception { File f=new File("c:/www/hits.txt"); FileOutputStream f2=new FileOutputStream(f); String str=Integer.toString(hits); byte buf[]=str.getBytes(); f2.write(buf); f2.close(); } public void filecache(int cache) throws Exception { File f=new File("c:/www/cache.txt"); FileOutputStream f2=new FileOutputStream(f); String str=Integer.toString(cache); byte buf[]=str.getBytes(); f2.write(buf); f2.close(); } public void filebytes(int bytes) throws Exception {

File f=new File("c:/www/bytes.txt"); FileOutputStream f2=new FileOutputStream(f); String str=Integer.toString(bytes); byte buf[]=str.getBytes(); f2.write(buf); f2.close(); } } import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.*; class GettingStart extends JFrame { GettingStart() { super("Get Start"); Container c=getContentPane(); setSize(350,400); setLocation(200,200); setResizable(false); show(); mywindowg mm=new mywindowg(this); addWindowListener(mm); } public void paint(Graphics g) { setBackground(Color.cyan); g.setFont(new Font("TimesRoman",Font.BOLD,20)); g.setColor(Color.black); String str="How to start WebServer"; g.drawString(str,20,70); g.setFont(new Font("TimesRoman",Font.PLAIN,16)); g.setColor(Color.black); str="Initially when you start web server."; g.drawString(str,20,90); str="it initialise itself and starts running.But if";

g.drawString(str,20,110); str="any problem occur.then click 'Run' in menu."; g.drawString(str,20,130); g.setFont(new Font("TimesRoman",Font.BOLD,20)); g.setColor(Color.black); str="Change configuration of WebServer"; g.drawString(str,20,160); g.setFont(new Font("TimesRoman",Font.PLAIN,16)); str="click on setting.change setting.click 'Ok'."; g.drawString(str,20,180); str="click 'Stop'.CLick 'Run'."; g.drawString(str,20,200); } public static void main(String args[]) { GettingStart gs=new GettingStart(); } class mywindowg extends WindowAdapter { GettingStart menu; public mywindowg(GettingStart menu) { this.menu=menu; } public void windowClosing(WindowEvent we) { menu.setVisible(false); } } } import java.io.*; /*httpresponse parse a return message and mime header from a server. http/1.0 302 found=redirection,check location for where. http/1.0 200 ok=file data comes after mime header.

*/ class HttpResponse { int statuscode; //status-code in spec String reasonPhrase; //reason phrase in spec mimeheader mh; static String CRLF="\r\n"; void parse(String request) { int fsp=request.indexOf(' '); int nsp=request.indexOf(' ',fsp+1); int eol=request.indexOf('\n'); String protocol=request.substring(0,fsp); statuscode=Integer.parseInt(request.substring(fsp+1,nsp)); reasonPhrase=request.substring(nsp+1,eol); String raw_mime_header=request.substring(eol+1); mh=new mimeheader(raw_mime_header); } HttpResponse(String request) { parse(request); } HttpResponse(int code,String reason,mimeheader m) { statuscode=code; reasonPhrase=reason; mh=m; } public String toString() { return "HTTP/1.0"+statuscode +" "+reasonPhrase+CRLF+mh+CRLF; } } /* The Server Class That Handles HTTP Requests

Author : */

Dattaraj J. Rao jagrao@goa1.dot.net.in

import java.net.*; import java.io.*; import java.util.*; public class HttpServer extends BaseServer implements Runnable { String docpath,defaultname,errorfilename,tempfilename; char sep; Thread t=null; Vector filters,alias; public HttpServer() { super(); sep=System.getProperty("file.separator").charAt(0); filters=new Vector(); alias=new Vector(); readFromFile(); } public void start() { if(t==null) { t=new Thread(this); t.start(); } } public void start(int p) { port=p; start(); }

public void stop() { if(t!=null) { t.stop(); t=null; super.stop(); } } //////////////////////////////////////////////////////// public int getPort() { return port; } public void setPort(int p) { port=p; } public String getDocpath() { return docpath; } public void setDocpath(String d) { docpath=d; } public char getSep() { return sep; } public String getDefaultname() { return defaultname;

} public void setDefaultname(String f) { defaultname=f; } public String getErrorFileName() { return errorfilename; } public void setErrorFileName(String f) { errorfilename=f; } public String getTempFileName() { return tempfilename; } public void setTempFileName(String f) { tempfilename=f; } public String[][] getAliasList(int rows) { String ret[][]=new String[rows][2]; String temp,oldval,newval; for(int i=0;i<alias.size();i++) { if(i>rows-1) break; temp=(String)alias.elementAt(i); oldval=temp.substring(0,temp.indexOf('=')); newval=temp.substring(temp.indexOf('=') +1,temp.length());

ret[i][0]=oldval; ret[i][1]=newval; } return ret; } public void setAliasList(String aliasarray[][]) { String temp; alias=new Vector(); /* for(int j=0;j<aliasarray.length;j++) { System.out.println(aliasarray[j][0]); System.out.println(aliasarray[j][1]); }*/ try { for(int i=0;i<aliasarray.length;i++) { temp=aliasarray[i][0]+"="+aliasarray[i][1]; //System.out.println(temp); if(!temp.equals("=")) alias.addElement(temp); } } catch(NullPointerException e) { } } public String checkFilters(String ext) { String ret=""; for(int i=0;i<filters.size();i++) { if(((String)filters.elementAt(i)).startsWith(ext+";"))

{ ret=((String)filters.elementAt(i)).substring(ext.length()+1); break; } } return ret; } public String checkAlias(String filename) { if(filename.charAt(0)!=sep) filename=sep+filename; String temp,oldval,newval; for(int i=0;i<alias.size();i++) { temp=(String)alias.elementAt(i); oldval=temp.substring(0,temp.indexOf('=')); newval=temp.substring(temp.indexOf('=') +1,temp.length()); if(filename.startsWith(oldval)) { filename=filename.substring(oldval.length(),filename.length()); filename=newval+filename; return filename; } } if(filename.charAt(0)==sep) filename=filename.substring(1); return filename; } public void readFromFile() { try {

BufferedReader in=new BufferedReader(new FileReader("MyServer.conf")); String text; while(!(text=in.readLine()).equals(null)) { //System.out.println(text); if(text.equals("[PORT]")) { try { port=Integer.parseInt(in.readLine()); } catch(Exception e) { } } else if(text.equals("[DOCUMENT_PATH]")) { setDocpath(in.readLine()); } else if(text.equals("[DEFAULT_FILE_NAME]")) { setDefaultname(in.readLine()); } else if(text.equals("[DIRECTORY_ALIAS]")) { while(!(text=in.readLine()).equals("")) alias.addElement(text); } } in.close(); } catch(IOException e) { docpath="/Uploads/Main/".replace('/',sep);

defaultname="index.html"; errorfilename="error.html"; alias.addElement(("/Pics/=/Pictures/").replace('/',sep)); } catch(NullPointerException e) { } tempfilename=docpath+"temp.raj"; filters.addElement("pl;\\Progra~1\\sambar41\\perl\\Perl.exe"); } public void writeToFile() { try { PrintWriter out=new PrintWriter(new FileOutputStream("MyServer.conf")); out.println("[PORT]"); out.println(getPort()); out.println(); out.println("[DOCUMENT_PATH]"); out.println(getDocpath()); out.println(); out.println("[DEFAULT_FILE_NAME]"); out.println(getDefaultname()); out.println(); out.println("[DIRECTORY_ALIAS]"); for(int i=0;i<alias.size();i++) out.println((String)alias.elementAt(i)); out.println(); out.close(); } catch(IOException e) {

} } //////////////////////////////////////////////////////// protected void handleRequest(Socket client) { (new ConnectionThread(client,this)).start(); } public void run() { super.start(); } ///////////////////////////////////////////////////////// } interface LogMessage { public void log(String msg); } import java.awt.*; import java.io.*; import java.net.*; import java.applet.*; import java.awt.event.*; class MainServer extends Frame implements ActionListener,ItemListener { String msg=" "; String str=" "; TextArea text; MenuItem item1,item2,item3,item4,item5,item6,item7,item8; CheckboxMenuItem auto_start; MainServer() {} MainServer(String title)

{ super("Web Server version-1.0"); setBackground(Color.cyan); MenuBar mbar=new MenuBar(); setMenuBar(mbar); Menu server=new Menu("Server"); server.add(item1=new MenuItem("Run")); server.add(item2=new MenuItem("Stop")); server.add(new MenuItem("-")); server.add(item4=new MenuItem("Exit")); mbar.add(server); Menu console=new Menu("Console"); console.add(item5=new MenuItem("Server Status")); console.add(new MenuItem("-")); console.add(item6=new MenuItem("Configuration")); mbar.add(console); Menu help=new Menu("Help"); help.add(item7=new MenuItem("How To Start")); help.add(new MenuItem("-")); help.add(item8=new MenuItem("About WebServer")); mbar.add(help); item1.addActionListener(this); item2.addActionListener(this); //item3.addActionListener(this); item4.addActionListener(this); item5.addActionListener(this); item6.addActionListener(this); item7.addActionListener(this); item8.addActionListener(this); mywindowadapter aw=new mywindowadapter(this); addWindowListener(aw); this.setLocation(400,50); this.setResizable(false); String str="Web Server (ver-1.0)"; text=new TextArea(str); text.setEditable(false); add(text); h1.start();

item1.setEnabled(false); try { str="Local url:127.0.0.1:"+h1.getport(); } catch(Exception e) {} text.append("\n"); text.append(str); repaint(); } public void paint(Graphics g) { g.drawString("",10,200); } String arg; public void exit() { System.exit(0); } ServerThread h1=new ServerThread(); public void actionPerformed(ActionEvent ae) { arg=(String)ae.getActionCommand(); if(arg.equals("Run")) { text.append("\n"); text.append("\n"); text.append("Server start"); text.append("\n"); try { text.append("Local url:127.0.0.1:"+h1.getport()); } catch(Exception e) {} h1.start(); item1.setEnabled(false); item2.setEnabled(true);

} else if(arg.equals("Stop")) { System.out.println("stop clicked"); text.append("\n"); text.append("Server stopped."); h1.stop(); item1.setEnabled(true); item2.setEnabled(false); } else if(arg.equals("Exit")) { h1.stop(); exit(); } else if(arg.equals("Server Status")) { h1.t.suspend(); show1 sh=new show1(); h1.t.resume(); } else if(arg.equals("Configuration")) { h1.t.suspend(); Passd pass=new Passd("Authentication"); h1.t.resume(); } else if(arg.equals("How To Start")) { h1.t.suspend(); GettingStart gs=new GettingStart(); h1.t.resume(); } else if(arg.equals("About WebServer")) { h1.t.suspend(); show sh=new show(); h1.t.resume(); } repaint();

} public void itemStateChanged(ItemEvent ie) { repaint(); } public static void main(String args[]) throws Exception { MainServer menu=new MainServer("web serevr"); menu.setSize(new Dimension(300,200)); menu.setVisible(true); } } class mywindowadapter extends WindowAdapter { MainServer menu; public mywindowadapter(MainServer menu) { this.menu=menu; } public void windowClosing(WindowEvent we) { System.exit(0); } } import java.util.*; class mimeheader extends Hashtable { void parse(String data) { StringTokenizer st=new StringTokenizer(data,"\r\n"); while(st.hasMoreTokens()) { String s=st.nextToken(); int colon=s.indexOf(':'); String key=s.substring(0,colon); String val=s.substring(colon+2); //skip":" put(key,val); }

} mimeheader() {} mimeheader(String d) { parse(d); } public String toString() { String ret=""; Enumeration e=keys(); while(e.hasMoreElements()) { String key=(String)e.nextElement(); String val=(String)get(key); ret+=key+":"+val+"\r\n"; } return ret; } //This simple function converts a mine string from //any variant from capitalization to a canonical form. //for example:CONTENT TYPE or content length to Content type, //or Content-length or CoNTeNT-LENgth to Content-Length. private String fix(String ms) { char chars[]=ms.toLowerCase().toCharArray(); boolean upcaseNext=true; for(int i=0;i<chars.length-1;i++) { char ch=chars[i]; if(upcaseNext && 'a'<=ch && ch<='z') { chars[i]=(char)(ch-('a'-'A')); } upcaseNext=ch=='-'; } return new String(chars); } public String get(String key) {

return(String)super.get(fix(key)); } public void put(String key,String val) { super.put(fix(key),val); } } import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Passc extends JFrame implements ActionListener { JLabel uname1,password1; JTextField uname; JPasswordField password; public Passc(String title) { super(title); Container c=getContentPane(); c.setLayout(new FlowLayout()); c.setBackground(Color.cyan); uname1= new JLabel("User Name"); c.add(uname1); uname1.setToolTipText("Enter new Username"); uname=new JTextField(20); c.add(uname); uname.addActionListener(this); password1=new JLabel("Password"); c.add(password1); password=new JPasswordField(20); c.add(password); password.addActionListener(this);

JButton change,cancel; change=new JButton("Change"); c.add(change); change.addActionListener(this); cancel=new JButton("Cancel"); c.add(cancel); cancel.addActionListener(this); setLocation(400,150); setResizable(false); setSize(325,150); show(); mywindow2 aw=new mywindow2(this); addWindowListener(aw); } public void actionPerformed(ActionEvent ae) { boolean flag=false; String str=ae.getActionCommand(); if(str.equals("Change")) { try { addpassword(); } catch(Exception e) {} setVisible(false); } else if(str.equals("Cancel")) { setVisible(false); } } public void addpassword() throws Exception { uname u=new uname(); String s=uname.getText();

String p=new String(password.getPassword()); u.passwrite(p); u.unamewrite(s); } } class mywindow2 extends WindowAdapter { Passc menu; public mywindow2(Passc menu) { this.menu=menu; } public void windowClosing(WindowEvent we) { menu.setVisible(false); } } import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Passd extends JFrame implements ActionListener { JLabel uname1,password1; JPasswordField password; JTextField uname; public Passd(String title) { super(title); Container c=getContentPane(); c.setLayout(new FlowLayout()); c.setBackground(Color.cyan); JLabel uname1=new JLabel("User Name"); uname1.setToolTipText("Enter User-name"); c.add(uname1); uname=new JTextField(20);

c.add(uname); uname.addActionListener(this); password1=new JLabel("Password"); c.add(password1); password=new JPasswordField(20); c.add(password); password.addActionListener(this); JButton ok,cancel; ok=new JButton("Ok"); c.add(ok); ok.addActionListener(this); cancel=new JButton("Cancel"); c.add(cancel); cancel.addActionListener(this); setLocation(400,50); setResizable(false); setSize(325,150); show(); } public static void main(String args[]) { Passd pa=new Passd("hi"); } public void actionPerformed(ActionEvent ae) { boolean flag=false; String str=ae.getActionCommand(); if(str.equals("Ok")) { try { flag=checkpassword(); } catch(Exception e) {}

if(flag) { try { Configure set=new Configure("configuration"); this.setVisible(false); } catch(Exception e) {} } else { uname.setText(null); password.setText(null); } } else if(str.equals("Cancel")) { setVisible(false); } } public boolean checkpassword() throws Exception { String pass2="",unam=""; password pass1=new password(); pass2=pass1.passread(); unam=pass1.unameread(); String s=uname.getText(); String p=new String(password.getPassword()); if(s.equals(unam) && p.equals(pass2)) { return true; } else { return false; } } } class mywindow extends WindowAdapter {

Passd menu; public mywindow(Passd menu) { this.menu=menu; } public void windowClosing(WindowEvent we) { menu.setVisible(false); } } import java.io.*; class password { password() {} public String passread() throws Exception { File f=new File("c:/www/password.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch; String s,p=""; for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } f1.close(); return p; } public String unameread() throws Exception { File f=new File("c:/www/uname.txt"); FileInputStream f1=new FileInputStream(f); int i=f1.available(),j; char ch; String s,p="";

for(j=0;j<=i-1;j++) { ch=(char)f1.read(); s=String.valueOf(ch); p=p+s; } f1.close(); return p; } } import java.net.*; import java.io.*; import java.text.*; import java.util.*; public class Server implements Runnable,LogMessage { private int port; static File root; private String docroot; //timeout for client connection static int timeout=0; public static LogMessage log; private Hashtable cache=new Hashtable(); private boolean stopflag; private static String version="1.0"; private static String mime_text_html="text/html"; private static String CRLF="\r\n"; private static String indexfile="index.html"; static ServerSocket acceptsocket; filewrite f1=new filewrite(); static Socket s; private static int buffer_size=8192; static String mt[]={ //mapping fromfile ext to mime type "txt","text/plane","html",mime_text_html, "htm","text/html","gif","image/gif", "jpg","image/jpg","jpeg","image/jpg", "class","application/octet-stream"}; static String defaultext="txt";

static PrintStream log1=null; protected static Properties props=new Properties(); protected static void p(String s) { System.out.println(s); } //print log file static String root1; protected static void log2(String s) { synchronized(log1) { log1.println(s); log1.flush(); } } static Hashtable types=new Hashtable(); static { for(int i=0;i<mt.length;i+=2) types.put(mt[i],mt[i+1]); } void loadprops() throws Exception { File f=new File(System.getProperty("user.dir")+File.separator+ "www-server.txt"); if(f.exists()) { InputStream inpst=new BufferedInputStream(new FileInputStream(f)); props.load(inpst); inpst.close(); String r=props.getProperty("root"); root1=r; if(r!=null) { root=new File(r); if(!root.exists()) { throw new Error(root+"doesn't exist as server root"); }

} r=props.getProperty("timeout"); if(r!=null) { timeout=Integer.parseInt(r); } r=props.getProperty("log1"); if(r!=null) { p("opening log files:"+r); log1=new PrintStream(new BufferedOutputStream(new FileOutputStream(r))); } } if(root==null) { root=new File(System.getProperty("user.dir")); } if(log1==null) { p("WEBSERVER version 1.0"); p("loging to stdout"); log1=System.out; } } static String fnametomimetype(String filename) { if(filename.endsWith("/")) { return mime_text_html; } int dot=filename.lastIndexOf('.'); String ext=(dot>0)?filename.substring(dot+1):defaultext; String ret=(String)types.get(ext); return ret!=null?ret:(String)types.get(defaultext); } public int hits_served=0; public int bytes_served=0; public int files_in_cache=0;

public int bytes_in_cache=0; public int hits_to_cache=0; private final byte toBytes(String s)[] { byte b[]=s.getBytes(); return b; } private mimeheader makemimeheader(String type,int length) { mimeheader mh=new mimeheader(); Date curdate=new Date(); TimeZone gmtz=TimeZone.getTimeZone("GMT+5.30"); SimpleDateFormat sdf=new SimpleDateFormat("dd mm yyyy hh:mm:ss zzz"); sdf.setTimeZone(gmtz); mh.put("Date",sdf.format(curdate)); mh.put("Server","final year project"); mh.put("Content -Type",type); if(length>=0) { mh.put("Content-Length",String.valueOf(length)); } return mh; } private String error(int code,String msg,String url) { String html_page="<body>"+CRLF+"<h1>"+code+" "+msg+"</h1>"+CRLF; if(url!=null) html_page+="Error when fetching URL:"+url+CRLF; html_page+="</body>"+CRLF; mimeheader mh=makemimeheader(mime_text_html,html_page.length()); HttpResponse hr=new HttpResponse(code,msg,mh); logEntry("GET",url,code,0); return hr+html_page; } //read 'in' until you get two\n's in a row. //return up tothat point as aStrig. //discard all /r's.

private String getrawrequest(InputStream in) throws IOException { byte buf[]=new byte[buffer_size]; int pos=0; int c; while((c=in.read())!=-1) { switch(c) { case '\r': break; case '\n': if(buf[pos-1]==c) { return new String(buf,0,pos); } default: buf[pos++]=(byte) c; } } return null; } static String months[]={ "jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct", "Nov","Dec"}; private String host; //fmt02d is the same as c's printf("%02d",i) private final String fmt02d(int i) { if(i<0) { i=-1; return((i<9)?"-0":"-")+i; } else { return((i<9)?"0":" ")+i; } }

public int hits() { return hits_served; } public int bytes_s() { return bytes_served; } private void logEntry(String cmd,String url,int code,int size) { Calendar calender=Calendar.getInstance(); int tzmin=calender.get(Calendar.ZONE_OFFSET)/(60*1000); int tzhour=tzmin/60; tzmin-=tzhour*60; String s=host+"- -["+fmt02d(calender.get(Calendar.DATE))+"/"+ months[calender.get(Calendar.MONTH)]+"/"+ calender.get(Calendar.YEAR)+":" +fmt02d(calender.get(Calendar.HOUR))+ ":"+fmt02d(calender.get(Calendar.MINUTE))+":"+ fmt02d(calender.get(Calendar.SECOND))+" "+fmt02d(tzhour)+ fmt02d(tzmin)+"]\""+cmd+" "+url+"HTTP/1.0\" "+code+" "+size+"\n"; log.log(host+"- -["+fmt02d(calender.get(Calendar.DATE))+"/"+ months[calender.get(Calendar.MONTH)]+"/"+ calender.get(Calendar.YEAR)+":" +fmt02d(calender.get(Calendar.HOUR))+ ":"+fmt02d(calender.get(Calendar.MINUTE))+":"+ fmt02d(calender.get(Calendar.SECOND))+" "+fmt02d(tzhour)+ fmt02d(tzmin)+"]\""+cmd+" "+url+"HTTP/1.0\" "+code+" "+size+"\n"); try { f1.fileaccess(s); } catch(Exception e) {} hits_served++; try {

f1.filehits(hits_served); } catch(Exception e) {} System.out.println(hits_served); bytes_served+=size; try { f1.filebytes(bytes_served); } catch(Exception e) {} System.out.println(bytes_served); //bytes_s(bytes_served); } private void writestring(OutputStream out,String s) throws IOException { out.write(toBytes(s)); } private void writeuce(OutputStream out,urlcacheentry uce) throws IOException { HttpResponse hr=new HttpResponse(200,"ok",uce.mh); writestring(out,hr.toString()); out.write(uce.data,0,uce.length); logEntry("GET",uce.url,200,uce.length); } private boolean serverfromcache(OutputStream out,String url) throws IOException { urlcacheentry uce; if((uce=(urlcacheentry)cache.get(url))!=null) { writeuce(out,uce); hits_to_cache++; try { f1.filecache(hits_to_cache); } catch(Exception e)

{} return true; } return false; } private urlcacheentry loadFile(InputStream in,String url,mimeheader mh) throws IOException { urlcacheentry uce; byte file_buf[]=new byte[buffer_size]; uce=new urlcacheentry(url,mh); int size=0; int n; while((n=in.read(file_buf))>=0) { uce.append(file_buf,n); size+=n; } in.close(); cache.put(url,uce); files_in_cache+=uce.length; return uce; } // private urlcacheentry readFile(File f,String url) throws IOException { if(!f.exists()) return null; InputStream in=new FileInputStream(f); int file_length=in.available(); String mime_type=fnametomimetype(url); mimeheader mh=makemimeheader(mime_type,file_length); urlcacheentry uce=loadFile(in,url,mh); return uce; } // private void writedisccache(urlcacheentry uce) throws IOException {

String path=docroot+uce.url; String dir=path.substring(0,path.lastIndexOf("/")); dir.replace('/',File.separatorChar); new File(dir).mkdirs(); FileOutputStream out=new FileOutputStream(path); out.write(uce.data,0,uce.length); out.close(); } //A client asks us for a url that looks like this: //http://www.rediff.com/the/url //we go get it from the site and return it..... private void handleproxy(OutputStream out,String url,mimeheader inmh) { try { int start=url.indexOf("://")+3; int path=url.indexOf('/',start); String site=url.substring(start,path).toLowerCase(); int port=80; String server_url=url.substring(path); int colon=site.indexOf(':'); if(colon>0) { port=Integer.parseInt(site.substring(colon+1)); site=site.substring(0,colon); } url="/cache/"+site+((port!=80)?(":"+port):" ")+server_url; if(url.endsWith("/")) url+=indexfile; if(!serverfromcache(out,url)) { if(readFile(new File(docroot+url),url)!=null) { serverfromcache(out,url); return; } //if we havn't already cached this page,open a socket //to the site's port and send a GET command to it. //we modify the user agent to add ourselves...."via". Socket server=new Socket(site,port);

InputStream server_in=server.getInputStream(); OutputStream server_out=server.getOutputStream(); inmh.put("User-Agent",inmh.get("User-Agent")+"via java web server"); String req="GET"+server_url+"HTTP/1.0"+CRLF+inmh+CRLF; writestring(server_out,req); String raw_request=getrawrequest(server_in); HttpResponse server_response=new HttpResponse(raw_request); writestring(out,server_response.toString()); if(server_response.statuscode==200) { urlcacheentry uce=loadFile(server_in,url,server_response.mh); out.write(uce.data,0,uce.length); writedisccache(uce); logEntry("GET",site+server_url,200,uce.length); } server_out.close(); server.close(); } } catch(IOException e) { log.log("Exception:"+e); } } private void handleget(OutputStream out,String url,mimeheader inmh) { byte file_buf[]=new byte[buffer_size]; String filename=docroot+url+(url.endsWith("/")?indexfile:" "); try { if(!serverfromcache(out,url)) { File f=new File(filename); if(!f.exists()) { writestring(out,error(404,"notfound",filename)); return; } if(!f.canRead()) {

writestring(out,error(404,"permission denied",filename)); return; } urlcacheentry uce=readFile(f,url); writeuce(out,uce); } } catch(IOException e) { log.log("Exception:"+e); } } private void dorequest(Socket s)throws IOException { System.out.println("dorequest called"); if(stopflag) return; System.out.println("request full"); InputStream in=s.getInputStream(); OutputStream out=s.getOutputStream(); String request=getrawrequest(in); int fsp=request.indexOf(' '); int nsp=request.indexOf(' ',fsp+1); int eol=request.indexOf('\n'); String method=request.substring(0,fsp); String url=request.substring(fsp+1,nsp); String raw_mime_header=request.substring(eol+1); mimeheader inmh=new mimeheader(raw_mime_header); request=request.substring(0,eol); if(method.equalsIgnoreCase("get")) { if(url.indexOf("://")>=0) { handleproxy(out,url,inmh); } else { handleget(out,url,inmh); } }

else { writestring(out,error(405,"method not allowed",method)); } in.close(); out.close(); } public void startserver() { try { acceptsocket=new ServerSocket(port); while (true) { s=acceptsocket.accept(); host=s.getInetAddress().getHostName(); dorequest(s); System.out.println("hi"+hits_served); s.close(); } } catch(IOException e) { log.log("accept loop IOException:"+e+"\n"); } catch(Exception e) { log.log("Exception:"+e); } } public void run() { startserver(); } public Thread t; public synchronized void start() {

if(t==null) { t=new Thread(this); t.start(); } } /*void stop1() throws Exception { System.out.println("stop called"); stopflag=true; System.out.println("socket to be closed"); acceptsocket.close(); s.close(); System.out.println("socket close"); log.log("stopped at"+new Date()+"\n"); System.out.println("error closing server"); } */ Server() {} Server(int p,String str,LogMessage lm) { port =p; if(str.equals(null)) { try { loadprops(); } catch(Exception e) {} docroot=root1; } else { docroot=str; } log=lm;

this.log=this; this.start(); try { Thread.currentThread().join(); } catch(InterruptedException e) {} } public void log(String m) { System.out.print(m); } } import java.io.*; class ServerThread extends Server implements Runnable { Thread t=null; fileread f=new fileread(); String path; int port; Server h; void ServerThread() { } public void stop1() { if(t!=null) { t.suspend(); } } public void start() { System.out.println("start"); t=new Thread(this); t.start();

} public void run() { try { System.out.println("getpath"); getpath(); System.out.println(port); System.out.println(path); } catch(Exception e) {} if(port==0) port=80; if(path.equals(null)) { path="c:\\www"; } h=new Server(port,path,null); } int getport() throws Exception { try { return port=f.fileport(); } catch(Exception e) {} return port; } void getpath() throws Exception { try { path=f.filepath(); port=f.fileport(); } catch(Exception e) {}

} public void stop() { try { if(t!=null) { t.stop(); t=null; h.acceptsocket.close(); h.s.close(); } } catch(Exception e) {} // catch(NullPointerException e) //{ //System.out.println("caught"); // } } } import java.awt.*; import java.util.*; import java.applet.*; import java.awt.event.*; import javax.swing.*; class show1 extends JFrame { String msg,msg1,msg2,arg; fileread f=new fileread(); JLabel hit,cache,bytess; show1() { super("Server Status"); Container c=getContentPane(); c.setBackground(Color.cyan); c.setLayout(new FlowLayout());

try { msg=f.filehits(); msg1=f.filebytes(); msg2=f.filecache(); } catch(Exception e) {} setLocation(400,150); setResizable(false); setSize(300,150); show(); mywindowrr mm=new mywindowrr(this); addWindowListener(mm); } public static void main(String args[]) { show1 sh=new show1(); } public void paint(Graphics g) { setBackground(Color.cyan); g.setFont(new Font("TimesRoman",Font.PLAIN,18)); g.setColor(Color.black); g.drawString("Total Hits:",30,50); g.drawString("Total Bytes:",30,70); g.drawString("Total Hits from cache:",30,90); g.setFont(new Font("TimesRoman",Font.PLAIN,18)); g.setColor(Color.red); g.drawString(msg,200,50); g.drawString(msg1,200,70); g.drawString(msg2,200,90); } }

class mywindowrr extends WindowAdapter { show1 menu; public mywindowrr(show1 menu) { this.menu=menu; } public void windowClosing(WindowEvent we) { //System.exit(0); menu.setVisible(false); } } import java.awt.*; import java.applet.*; import java.awt.event.*; import javax.swing.*; class show extends JFrame { String str; show() { super("WebServer"); Container c=getContentPane(); c.setLayout(new FlowLayout()); //c.setBackground(Color.cyan); setSize(300,200); setLocation(400,50); setResizable(false); show(); mywindowr mm=new mywindowr(this); addWindowListener(mm); } public void paint(Graphics g) { setBackground(Color.cyan); g.setFont(new Font("TimesRoman",Font.BOLD,24));

g.setColor(Color.black); g.drawString("WEB SERVER",20,50); g.setFont(new Font("TimesRoman",Font.PLAIN,16)); g.setColor(Color.black); g.drawString("version 1.0",185,50); g.setFont(new Font("TimesRoman",Font.PLAIN,18)); g.setColor(Color.black); g.drawString("developed by:",150,80); g.setFont(new Font("TimesRoman",Font.ITALIC,16)); g.setColor(Color.black); g.drawString("Anurag Yadav",150,95); g.drawString("Anand Prakash",150,109); g.drawString("B.Tech Final year",150,123); g.drawString("Submitted to: ",20,80); g.drawString("Mrs.Preeti Gupta",20,95); String msg="Note:This product is freeware.Try it."; String msg1="Meet me at 'anurag042@rediffmail.com'."; g.setFont(new Font("TimesRoman",Font.ITALIC,12)); g.setColor(Color.black); g.drawString(msg,20,155); g.drawString(msg1,28,170); } public static void main(String args[]) { show s=new show(); } } class mywindowr extends WindowAdapter { show menu; public mywindowr(show menu) { this.menu=menu; }

public void windowClosing(WindowEvent we) { menu.setVisible(false); } } import java.io.*; class uname { uname() { } public void passwrite(String str) throws Exception { File f=new File("c:/www/password.txt"); FileOutputStream f2=new FileOutputStream(f); byte buf1[]=str.getBytes(); f2.write(buf1); f2.close(); } public void unamewrite(String str) throws Exception { File f=new File("c:/www/uname.txt"); FileOutputStream f2=new FileOutputStream(f); byte buf1[]=str.getBytes(); f2.write(buf1); f2.close(); } } class urlcacheentry { String url; mimeheader mh; byte data[]; int length=0; public urlcacheentry(String u,mimeheader m)

{ url=u; mh=m; String c1=mh.get("Content Length"); if(c1!=null) data=new byte[Integer.parseInt(c1)]; } void append(byte d[],int n) { if(data==null) { data =new byte[n]; System.arraycopy(d,0,data,0,n); length=n; } else { if(length+n>data.length) { byte old[]=data; data=new byte[old.length+n]; System.arraycopy(old,0,data,0,old.length); System.arraycopy(d,0,data,old.length,n); } else { System.arraycopy(d,0,data,length,n); length+=n; } } } }

Testing
Software testing is the process of executing software in a controlled manner, in order to answer the question: Does the software behave as specified? In this process we execute a program and try to find errors in the code. It is the process of exercising or evaluating a system or system component by manual or automatic means to verify that it satisfies specified requirements or to identify differences between expected and actual results. Testing should be thought of as an integral part of the software process and an activity that must be carried out throughout the life cycle. Each phase of software life cycle has a distinct product such as requirement specification, program unit design, program unit code, etc. Each end product can be checked for conformance with a previous phase and against the original requirements. Thus, errors can be detected at each phase of development. Software testing is often used in association with the terms verification and validation: Verification is the process of evaluating end product of each phase to ensure consistency with the end product of the previous phase. Validation is the process of testing software, or a specification, to ensure that it matches user requirements. Objectives of software testing: Software testing is usually performed for the following objectives: Software quality improvement Verification and validation Software reliability estimation

Testing required during different steps: The types of testing required during several steps of software development are described below: 1. Requirements and specifications: Requirements must be reviewed with the client. Rapid prototyping can refine requirements and accommodate changing requirements. The specification documents must be checked for feasibility, traceability, completeness, and absence of contradictions and ambiguities. 2. Design: The design must be checked for logic faults, interface faults, lack of exception handling, and non-conformance to specifications. 3. Coding: Code modules are informally tested by the programmer while they are being implemented Thereafter, formal testing of modules is done methodically by a testing team 4. Integration: Integration testing is performed to ensure that the modules combine together correctly to achieve a product that meets its specifications. 5. Product testing: The functionality of the product as a whole is checked against its specifications. The product is also tested for robustness (error-handling capabilities and stress tests) All source code and documentation are checked for completeness and consistency. 6. Acceptance testing: The software is delivered to the client, who tests the software on the actual hardware, using actual data instead of test data.

A product cannot be considered to satisfy its specifications until it has passed an acceptance test. 7. Maintenance: Modified versions of the original product must be tested to ensure that changes have been correctly implemented. Testing of Web Server In the web server we have performed testing at several levels. As we have discussed earlier in the introduction of testing about the testing at each stage. In the web server we test each module using unit testing strategy in which we provide stub for each module and test the result of each module. We have done path testing to check various paths so that the chances of bug can be minimized. At last we have performed integration testing by integrating all the modules together. Some of the bugs are found which are removed properly and also some improvement in the performance is obtained due to improvement in the software.

Output/Result
User Interface development
The interface developed in the web server are according to the requirements obtained in the requirement/analysis phase and the output obtained is according to the design in the system design phase. The user interfaces obtained as a result are here with a brief description:

Web Server Main window

This window is the first appeared window of web server. This window is the main window of the web server through which we can control our web server and also we can move to different windows just by clicking at the menu items appeared over this window. This window has three menu items: Server, Console and Help which are clearly shown in the figure. In the Server menu we have the options to control web server i.e. we have run,

stop and Exit menu through which we can run our web server, stop our web server and also close the web server. In the console menu item we have two menu items: Server Status and Configuration menu. By clicking at the Server Status we can open the window which shows the stats of our web server. By clicking at Configuration we can go for change in the configuration of the web server. In the Help menu we have two menu items: How to Start and About Web Server. By clicking at How to Start we can go for guidelines related to web server and by clicking at About Web Server we can know about the developer of web server.

Server Status window

Server Status window is the second user interface designed for the web server. The purpose behind designing this window is to show the server statistics to the end user that how much request are fulfilled by the web server. Total hits indicate the total no. of request fulfilled by the server while Total Bytes indicate the size if output delieverd till now via web server .Total hits from cache indicate the no. of request handled by the proxy server.

Authentication

Authentication window is another window which appears when user wants o change the configuration of the server or wants to change the username and password. In this window we have two text boxes to enter username and password. If on clicking Ok both entries are correct then only you can go for next step otherwise this window will not disappear till you clicked Cancel. On entering wrong entries text boxes will get null and wait for another entry.

Configuration

Configuration window is designed to fulfill the requirement of configuration change in the web server. In the configuration window we have two text fields for path of the root directory and port no... If any of the field in the interface is kept blank and you

clicked Ok then it will not change the configuration and also does not get disappeared from the desktop. In the configuration window we have one more option in the form of Change Password button, with the help of which you can switch to another interface for changing password and username.

Change Password

In the Change Password window we tried authorize user to provide the option to change the username and password. In this window we have two text fields which can not be kept blank i.e. if you want to change only password and left another field blank then you get failed. So you must fill both the entries and then click Change to make changes effective. You can click Cancel if you do not want to change the settings related to authentication.

About Web Server

About Web server interface is created to fulfill the requirement of providing knowledge about developer of the web server to the end user.

Get Start

Get Start interface is designed to meet the requirement of providing guidelines to the user about web server. In this

interface we add the guidelines for changing configuration of web server as well as guideline for running the web server. This window is activated by clicking in main window at Help->Get Start.

Log Entry Window (DOS)

This window of MS DOS represents the log entry of the request fulfilled by the server when a request is responded by the server.

Limitation
The web server developed by us has certain limitations which can be overcome in the future. Our web server possesses certain limitations which are as follows: 1. It only support GET and HEAD method of HTTP .Except this in other methods it invoke error. 2. It provides user a little flexibility i.e. only one user can handle this at any time. 3. The web server can run only when JVM is installed on the system. 4. The web server does handle CGI (common gateway interface).

Conclusion

Finally we have successfully developed the Web Server. It becomes possible due to the proper guidance provided by Ms. Preeti Gupta, faculty member of Computer Science & Engineering, Lucknow. Web server is able to successfully perform all the functions which are given in its specifications. It is GUI based which makes it user-friendly. It successfully handles the entire request made to it by responding client in a proper manner. However, my knowledge index with Java programming is not that high. There only the essential modules would be coded for the time being and rest of the specifications form a part of future work. Mainly the features and constructs to be considered would be Security measures and efficient user authentication. Handling of the basic requests Efficient user interfaces for users statistics of the servers performance But, after developing Web Server we earn very much confidence and experience in developing software, and we also becomes familiar with java and web related problems and protocols used over Internet for transmission of messages.

Future Scope

The web server has limitations in handling the request as it handles basic request and due to lack of knowledge and time we are not able to proceed further for the up gradation of the project. In the current we have tried to fulfill the basic requirements of the server. In the future the software can be upgraded to make it more secure and powerful and user can get more flexibility with the software which are the limitations of this project at present.

Bibliography

Name
Woods, Pekowky, Snee Dietel & Dietel Herbert Schildt Pressman Roser S.

Title
The developers guide to the Java Web Server Java How to Program The Complete Reference to Java 2 Software Engineering A Practitioners Approach

Year
1999 2001 2002 2001

You might also like