Child function that accepts multiple threads

need to do the child function that accepts multiple threads

Page 1 of 1

1 Replies - 2978 Views - Last Post: 17 October 2006 - 06:40 AM Rate Topic: -----

#1 Biancar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 16-October 06

Child function that accepts multiple threads

Posted 16 October 2006 - 06:40 AM

I had to implement a simple HTTP server that generates HTTP 1.1 responses GET requests. The servers starts by reading its port number and two configuration files. The first configuration file contains the absolute paths to the static documents directory and to the CGI programs directory, respectively. The second configuration file stores the mappings betwwen file extensions and MIMO types. The server continuously listens on its port number for incoming requests. Upon receiving a request the server creates a new thread for processing the request and keeps listening on the same port. The newly created thread generates the proper HTTP response, sends it back to the client and terminates. The response must include the required headers (e.g., Content-type, Content-length) and should be correctly displayed by a browser. You need to ensure that the server is capable of serving multiple requests in parallel. Also, the server is required to: check for the necessary request headers (e.g., Content Type) and generate a "400 Bad Requst" response if the request is not properly formed. Check for the existence of the requeired file /CGI program and generate a "404 Not found" response if the file does not exist. Generate a "501 Not implemented" response for HEAD and POST request.
I had to implement the program starting only from the socket API. This program I did accepts one connection at a
time, we need to make the child function that accepts multiple connections and uses the threads (I'm not familiar with that)
import java.io.*;
import java.net.*;
import java.util.Date;

public class WebServer
{

	private static String PERLS[][] ={
  {"Experience keeps a dear school, yet  fools  will  learn in no other.",
   "Benjamin  Franklin" }};

	public static void sendHeader(PrintWriter out)
	{
		Date date = new Date();
		out.println("HTTP/1.1 200 OK");
		out.println("Date: " + date);
		out.println("Server: BWS (Super-charged)");
		out.println("Content-Type: text/html; charset=UTF-8");
		out.println();
		out.flush();
	}

	public static void sendPage(PrintWriter out)
	{//this is where we send the files
		int quoteID = (int) (PERLS.length * Math.random());
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Today's   Quote</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<hl>Today's   Quote</hl>");
		out.println("<p><i>" + PERLS[quoteID][0] + "</ix/p>");
		out.println("<blockquote>");
		out.println("<b>" + PERLS[quoteID][1] + "</b>");
		out.println("</blockquote>");
		out.println("</body>");
		out.println("</html>");
		out.println();
		out.flush();
	}

	public  static void servePageTo (Socket  connection,   boolean logHeader)
	{
		try
		{
			OutputStream outStream = connection. getOutputStream( );
			PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream));
			
			InputStream inStream = connection.getInputStream();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
			String line = in.readLine ();
			while ((line != null) && (!line.trim().equals("")))
			{
				if (logHeader)
					System.out.println("HEADER: " + line); 
				line = in.readLine();
			}
			sendHeader(out); sendPage(out);
			in.close ();
			out.close ( );
			connection.close ( ); 
		}
		catch (IOException ioe)
		{   
			System.err.println ( "lOException: " + ioe);  
		}
	}	

	public static void startServer(String port, boolean logHeader)
	{
		try
		{
			ServerSocket server = new ServerSocket(Integer.parseInt(port));
			logMsg("Server started: " + server);
			boolean serverUp = true;
			while (serverUp)
			{
				Socket connection = server.accept();
				logMsg("Server connected: " + connection);
				servePageTo(connection, logHeader);
				logMsg("Server disconnected: " + connection);
			}
			server.close();

			logMsg("Server closed.");
		}
		catch (Exception ex)
		{
			System.err.println("Server startup error: " + ex);
		}
	}

	public static void logMsg(String msg)
	{
		Date d = new Date();
		System.out.println("[" + d + "] " + msg);
	}

	public static void main(String args[])
	{
		System.out.println("\nServes web pages according to HTTP/1.1.\n");
		if (args.length == 1)
			startServer(args[0], false);
		else if (args.length == 2)
			startServer(args[0], true);
		else
			System.out.println("\n\tUsage: Java Webserver port [ logHeader ]\n");
	}
}
/**  Simulates a simple but working Web client, retrieving HTTP header and page data.*/
import java.io.*;
import java.net.*;

public class WebClient
{
	public static void getHeader(String host, String port, String file, boolean headerOnly)
	{
		try
		{   // Showing some basic connection information
			Socket connection = new Socket(host, Integer.parseInt(port));
			System.out.print("Connect from ");
			System.out.print(connection.getLocalAddress());
			System.out.print(":" + connection.getLocalPort());
			System.out.println(" to " + connection);
			// Stream for output (sending) text
			OutputStream outStream = connection.getOutputStream();
			PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream));
			// Stream for input (receiving) text
			InputStream inStream = connection.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
			// Sending standard HTTP 1.1 GET request
			out.println("GET " + file + " HTTP/1.1");
			out.println("Host: " + host + ":" + port);
			out.println();
			out.flush();
			// Reading incoming data (optionally only header)
			boolean headerDone = false;
			String line = in.readLine();
			while ((line != null) && (!headerDone))
			{
				System.out.println("Read: " + line);
				line = in.readLine();
				if ((headerOnly) && (line.trim().equals("")))
					headerDone = true;
			}
			// Closing streams and connection
			in.close();
			out.close();
			connection.close();
		}
		catch (UnknownHostException uhe)
		{   System.err.println("Unknown host: " + host);  }
		catch (IOException ioe)
		{   System.err.println("IOException: " + ioe);	}
	}
	
	public static void main(String args[])
	{
		System.out.println("\nRetrieves data using an HTTP 1.1 GET request.\n");
		if (args.length == 3)
			getHeader(args[0], args[1], args[2], false);
		else if (args.length == 4)
			getHeader(args[0], args[1], args[2], true);			
		else
			System.out.println("\n\tUsage: java WebClient host port file [header-only]\n");
	}
}


please help me!

[edit]code tages[/edit]

This post has been edited by Amadeus: 16 October 2006 - 07:28 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Child function that accepts multiple threads

#2 Java_N1ZJA  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 25-August 06

Re: Child function that accepts multiple threads

Posted 17 October 2006 - 06:40 AM

hey biancar

when working with multiple threads you need to "create" a new "listener" everytime a connection is requested.

what you could do is to create a new class that implements Runnable which you require to use threads, and in the new class do you create the new Socket for the connection.

while(serverUP) {
	try {
		new Session(ss.accept());
	}catch(IOException ioe) {
		// do whatever
	}
}

//This will be the new class you make to create a new session for all the connections
	
Class Session implements Runnable {
	Socket soc;
	BufferedReader br;
	PrintWriter pw;
	Thread runner;
	
	Session(Socket s) {
		soc = s;
		//this try...catch part is usefull when you want to
		//send messages between server/client to check 
		//that the server and client communicate right
		try {
			br = new BufferedReader(new InputStreamReader(
					soc.getInputStream()));
			pw = new PrintWriter(new BufferedOutputStream(
					soc.getOutputStream()),true);
			pw.println("You are now connected");
		} catch(IOException ioe) {
			// do whatever
		}
		//start the thread
		if (runner == null) {
			runner = new Thread(this);
			runner.start();
		}
	}
	
	public void run() {
		while (runner == Thread.currentThread()) {
			// here is where you put function calls
			// like the servePageTo() func in your code
		
			//to stop the thread
			runner = null;
			pw.close();
			br.close();
			soc.close();
		}
	}


sorry if its a bit confusing. Let me know if there is any other problems.

thanks

:ph34r:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1