Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am developing a android app which turns the android device into a multithreaded web server the code which i use do not have any error but runs fine and it can be seen through web browser but it shows the source of html file as text rather than full gui.

this is my code..

Jhtts class:

package dolphin.developers.com;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import dolphin.devlopers.com.R;

public class JHTTS extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);

        setContentView(R.layout.server);

        try {

            String IndexFileName = "index.htm";
            File documentRootDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/");
            JHTTP j = new JHTTP(documentRootDirectory, 9001, IndexFileName);
            j.start();

            Toast.makeText(getApplicationContext(), "Server Started!!", 5).show();
            Log.d("Server Rooot", "" + documentRootDirectory);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
    }
}

Jhttp class:

package dolphin.developers.com;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class JHTTP extends Thread {

    private File documentRootDirectory;
    private String indexFileName = "index.htm";
    private ServerSocket server;
    private int numThreads = 50;

    public JHTTP(File documentRootDirectory, int port, String indexFileName) throws IOException {

        if (!documentRootDirectory.isDirectory()) {

            throw new IOException(documentRootDirectory

            + " does not exist as a directory");
        }

        this.documentRootDirectory = documentRootDirectory;
        this.indexFileName = indexFileName;
        this.server = new ServerSocket(port);
    }

    public JHTTP(File documentRootDirectory, int port) throws IOException {
        this(documentRootDirectory, port, "index.htm");
    }

    public JHTTP(File documentRootDirectory) throws IOException {
        this(documentRootDirectory, 9001, "index.htm");
    }

    public void run() {
        for (int i = 0; i < numThreads; i++) {
            Thread t = new Thread(new RequestProcessor(documentRootDirectory, indexFileName));
            t.start();
        }
        System.out.println("Accepting connections on port " + server.getLocalPort());
        System.out.println("Document Root: " + documentRootDirectory);

        while (true) {
            try {
                Socket request = server.accept();

                request.setReuseAddress(true);
                RequestProcessor.processRequest(request);

            } catch (SocketException ex) {

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

RequestProcessor:

package dolphin.developers.com;

import java.net.*;
import java.io.*;
import java.util.*;


          public class RequestProcessor implements Runnable {

           @SuppressWarnings("rawtypes")
        private static List pool = new LinkedList( );

           private File documentRootDirectory;

           private String indexFileName = "index.html";

           public RequestProcessor(File documentRootDirectory,

           String indexFileName) {


        if (documentRootDirectory.isFile( )) {

        throw new IllegalArgumentException(

        "documentRootDirectory must be a directory, not a file");

        }

       this.documentRootDirectory = documentRootDirectory;

       try {

    this.documentRootDirectory

    = documentRootDirectory.getCanonicalFile( );

    }


    catch (IOException ex) {

    }

    if (indexFileName != null) this.indexFileName = indexFileName;

    }


    @SuppressWarnings("unchecked")
    public static void processRequest(Socket request) {
    synchronized (pool) {
    pool.add(pool.size( ), request);
    pool.notifyAll( );

    }

    }

   public void run( ) {
// for security checks

  String root = documentRootDirectory.getPath( ); 
  while (true) {
  Socket connection;

  synchronized (pool) {

  while (pool.isEmpty( )) {

  try {

  pool.wait( );
}



 catch (InterruptedException ex) {


 }

 }


    connection = (Socket) pool.remove(0);

      }

   try {


   String filename;

   String contentType;

   OutputStream raw = new BufferedOutputStream(

   connection.getOutputStream( )


   );


   Writer out = new OutputStreamWriter(raw);




   Reader in = new InputStreamReader(

   new BufferedInputStream(

   connection.getInputStream( )

   ),"ASCII"

   );


     StringBuffer requestLine = new StringBuffer( );

     int c;

     while (true) {

     c = in.read( );
     if (c == '
' || c == '
') break;
     requestLine.append((char) c);

     }

          String get = requestLine.toString( );
// log the request

       System.out.println(get);

       StringTokenizer st = new StringTokenizer(get);

       String method = st.nextToken( );

       String version = "";

       if (method.equals("GET")) {

       filename = st.nextToken( );

       if (filename.endsWith("/")) filename += indexFileName;

       contentType = guessContentTypeFromName(filename);

       if (st.hasMoreTokens( )) {

       version = st.nextToken( );
}
   File theFile = new File(documentRootDirectory,
   filename.substring(1,filename.length( )));
   if (theFile.canRead( )
 // Don't let clients outside the document root
   && theFile.getCanonicalPath( ).startsWith(root)) {

   DataInputStream fis = new DataInputStream(

   new BufferedInputStream(

  new FileInputStream(theFile)
 )

   );
   byte[] theData = new byte[(int) theFile.length( )];
   fis.readFully(theData);
   fis.close( );
   if (version.startsWith("HTTP ")) { // send a MIME header

  out.write("HTTP/1.0 200 OK
");


  Date now = new Date( );
  out.write("Date: " + now + "
");
  out.write("Server: JHTTP/1.0
");
  out.write("Content-length: " + theData.length + "
");
  out.write("Content-type: " + contentType + "

");
  out.flush( );

  } // end if
// send the file; it may be an image or other binary data
// so use the underlying output stream
// instead of the writer
 raw.write(theData);
 raw.flush( );

  } // end if

   else { // can't find the file

   if (version.startsWith("HTTP ")) { // send a MIME header

   out.write("HTTP/1.0 404 File Not Found
");

  Date now = new Date( );

  out.write("Date: " + now + "
");

  out.write("Server: JHTTP/1.0
");

  out.write("Content-type: text/html

");

   }

   out.write("<HTML>
");
   out.write("<HEAD><TITLE>File Not Found</TITLE>
");
   out.write("</HEAD>
");
   out.write("<BODY>");

    out.write("<H1>HTTP Error 404: File Not Found</H1>
");
    out.write("</BODY></HTML>
");
    out.flush( );

  }

  }

  else { // method does not equal "GET"

  if (version.startsWith("HTTP ")) { // send a MIME header

  out.write("HTTP/1.0 501 Not Implemented
");

  Date now = new Date( );

  out.write("Date: " + now + "
");

  out.write("Server: JHTTP 1.0
");

  out.write("Content-type: text/html

");

   }

   out.write("<HTML>
");
   out.write("<HEAD><TITLE>Not  Implemented</TITLE>
");
   out.write("</HEAD>
");
   out.write("<BODY>");
   out.write("<H1>HTTP Error 501: Not Implemented</H1>
");

   out.write("</BODY></HTML>
");

   out.flush( );

  } 

  }

   catch (IOException ex) {

  }

   finally {

   try {

  connection.close( );

  }

  catch (IOException ex) {}

 }
 } // end while

  } // end run

    public static String guessContentTypeFromName(String name) {

    if (name.endsWith(".html") || name.endsWith(".htm")) {

    return "text/html";

    }

    else if (name.endsWith(".txt") || name.endsWith(".java")) {

    return "text/plain";


    }


    else if (name.endsWith(".gif")) {

    return "image/gif";

    }

    else if (name.endsWith(".class")) {

    return "application/octet-stream";

 }


     else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) {  


     return "image/jpeg";

   }

     else if (name.endsWith(".png") ) {  


         return "image/png";

       }

     else if (name.endsWith(".js")) {  


         return "text/javascript";

       }

     else if (name.endsWith(".js")) {  


         return "text/javascript";

       }

     else if (name.endsWith(".css")) {  


         return "text/css";

       }

   else return "text/plain";

   }


   } // end RequestProcessor

Please Help...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
106 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...