Just Simple Info

Pages

Android as Web Server

set android as web server


This sample code is about how to set android device as your web server on local network.
It may use to develop android application which need to transfer file from your laptop or desktop without need of any application in client side just a browser.

Below is the file structure.




Below is the code snippet.

1. MainActivity.java


package blogspot.justsimpleinfo.com.androidwebserver;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,Server.ServerListener {


    TextView mStatusTextView;
    EditText mPortEditText;
    Button mStartServerButton;
    Button mStopServerButton;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        this.mStatusTextView = this.findViewById(R.id.status_textview);
        this. mPortEditText = this.findViewById(R.id.port_edittext);
        this.mStartServerButton = this.findViewById(R.id.start_server_btn);
        this.mStartServerButton.setOnClickListener(this);

        this.mStopServerButton = this.findViewById(R.id.stop_server_btn);
        this.mStopServerButton.setOnClickListener(this);

    }

    Server mServer;


    @Override
    public void onClick(View view) {

        String stringPort = mPortEditText.getText().toString().trim();

        if(mServer ==null){


            mServer =  new Server(this,this);



        }



        if(view.getId() == R.id.start_server_btn){

            if(stringPort.length() >0 ){

                mServer.startServer(Integer.parseInt(stringPort));

            }else{


                mServer.startServer();
            }



        }else{
            mServer.stopServer();
        }



    }


    @Override
    public void onStart(final String ipAddress, final int port) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mStatusTextView.setGravity(Gravity.CENTER);
                mStatusTextView.setText("Running\r\n"+ipAddress+":"+port);
            }
        });
    }

    @Override
    public void onStop(String reason) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mStatusTextView.setGravity(Gravity.CENTER);
                mStatusTextView.setText("Not Running");
            }
        });

    }
}


2) Server.java



package blogspot.justsimpleinfo.com.androidwebserver;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Lauro-PC on 3/9/2018.
 */

public class Server implements Runnable {

    private final static String TAG = "Server";
    private boolean doServerRunning = false;
    private int mPort = 4000;
    private ServerSocket mServerSocket;
    BrowserRequestHandler mBrowserRequestHandler;
    ServerListener mServerListener;

    Server(int port, Context context,ServerListener serverListener){

        this.mPort = port;
        this.mBrowserRequestHandler = new BrowserRequestHandler(context);
        this.mServerListener = serverListener;
    }

    Server(Context context,ServerListener serverListener){

        mBrowserRequestHandler = new BrowserRequestHandler(context);
        this.mServerListener = serverListener;
    }

    public void startServer(int port){

        mPort = port;

        if(doServerRunning){
            /**
             * if server is running do nothing
             */
            return;
        }
        /**
         * start thread to start server listening to client
         */
        doServerRunning = true;
        new Thread(this).start();


    }

    public void startServer(){

        if(doServerRunning){
            /**
             * if server is running do nothing
             */
            return;
        }
        /**
         * start thread to start server listening to client
         */
        doServerRunning = true;
        new Thread(this).start();


    }
    public void stopServer(){


            try {

                doServerRunning = false;

                    if (mServerSocket != null) {
                        mServerSocket.close();
                        mServerSocket = null;

                    }


            } catch (Exception e) {

                Log.e(TAG, "Erro stoping server ", e);

            }finally {

                mServerListener.onStop("stop");

            }



    }

    @Override
    public void run() {




        try {

            this.mServerListener.onStart(getLocalIpAddress(),mPort);
            mServerSocket = new ServerSocket(mPort);
            while (doServerRunning) {

                Socket socket = mServerSocket.accept();
                mBrowserRequestHandler.handlerBrowserRequest(socket);

                socket.close();


            }



        } catch (SocketException e) {
            Log.e(TAG, "Server has error", e);
        } catch (IOException e) {
            Log.e(TAG, "Server has error", e);
        } catch (Exception e) {
            Log.e(TAG, "Server has error.", e);
        }



    }
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    interface ServerListener{
        void onStart(String ipAddress, int port);
        void onStop(String reason);
    }
}

3) BrowserRequestHandler.java



package blogspot.justsimpleinfo.com.androidwebserver;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Date;

/**
 * Created by Lauro-PC on 3/9/2018.
 */

public class BrowserRequestHandler {

    private String TAG = "BrowserRequestHandler";
    private AssetManager mAssetManager;
    private Context mContext;

    public BrowserRequestHandler(Context context){
        this.mContext = context;
        this.mAssetManager = context.getResources().getAssets();
    }
    public void handlerBrowserRequest(Socket socket){

        PrintStream output = null;
        BufferedReader reader = null;

        try{


            String route = null;

            // Read HTTP headers and get url requested
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String line;

            while (!TextUtils.isEmpty(line = reader.readLine())) {

                if (line.startsWith("GET /")) {

                    int start = line.indexOf('/') + 1;
                    int end = line.indexOf(' ', start);
                    route = line.substring(start, end);
                    break;
                }
            }


            byte[] contentBytes;

            if(route == null || route.isEmpty()){
                /**
                 * if route is empty serve home.html
                 */
                route = "home.html";

            }

            /**
             *
             */
            route = processUrl(route);


            if(route.startsWith("news") || route.startsWith("contact") || route.startsWith("about")){


                route = route+".html";

                contentBytes = WebFileHandler.getFile(route,mAssetManager);

            }else{

                contentBytes = WebFileHandler.getFile(route,mAssetManager);
            }


            output = new PrintStream(socket.getOutputStream());

            /**
             * set header and content type
             */
            output.println("HTTP/1.0 200 OK");
            output.println("Content-Type:"+ WebFileHandler.detectMimeType(route));


            output.println();
            output.write(contentBytes);
            output.flush();

        }catch (Exception e){

            try {
                if (null != output) {
                    output.close();
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }


    }

    /**
     *
     * @param url
     * @return
     */
    private String processUrl(String url){
        String urlTrim = url.trim();
        String splitedURL[] = urlTrim.split("/");

        if(splitedURL.length >= 2 &&(urlTrim.endsWith(".js") || urlTrim.endsWith(".css")) ){


            return splitedURL[splitedURL.length - 1];

        }

        return splitedURL[0];

    }
}

4) WebFileHandler.java




package blogspot.justsimpleinfo.com.androidwebserver;

import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Lauro-PC on 3/9/2018.
 */

public class WebFileHandler {

    public static final String HTML_MIME_TYPE = "text/html";
    public static final String JAVASCRIPT_MIME_TYPE = "application/javascript";
    public static final String CSS_MIME_TYPE = "text/css";
    public static final String FILE_MIME_TYPE = "application/octet-stream";

    public static String detectMimeType(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;

        } else if (fileName.endsWith(".html")) {

            return HTML_MIME_TYPE;
        } else if (fileName.endsWith(".js")) {


            return JAVASCRIPT_MIME_TYPE;

        } else if (fileName.endsWith(".css")) {

            return CSS_MIME_TYPE;

        } else {

            return FILE_MIME_TYPE;

        }
    }

    /**
     * get File
     * @param fileName
     * @param mAssetManager
     * @return
     */
    public static byte[] getFile(String fileName,AssetManager mAssetManager){

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream input = null;

        try {

            String htmlReponse = "";

            if(WebFileHandler.detectMimeType(fileName) == HTML_MIME_TYPE){
                /**
                 * html file is requested
                 */
                String indexHtmlFile = WebFileHandler.readHtmlFileString("index.html",mAssetManager,input);
                String htmlRequested = WebFileHandler.readHtmlFileString(fileName,mAssetManager,input);

                htmlReponse = indexHtmlFile.replaceAll("<!--CONTENT HERE IF NOT HOME!-->",htmlRequested);

                return htmlReponse.getBytes();
            }

            /**
             * if not html file requested
             */
            input = mAssetManager.open(fileName);
            byte[] buffer = new byte[1024];
            int size;
            while (-1 != (size = input.read(buffer))) {
                byteArrayOutputStream.write(buffer, 0, size);
            }
            byteArrayOutputStream.flush();
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();

            return null;

        }finally {

            try{

                if(input != null){
                    input.close();
                }

            }catch (Exception e){
                e.printStackTrace();
            }

        }


    }

    /**
     * Read html file
     * @param fileName
     * @param mAssetManager
     * @param inputStream
     * @return
     * @throws IOException
     */
    protected static String readHtmlFileString(String fileName,AssetManager mAssetManager, InputStream inputStream) throws IOException {
        inputStream = mAssetManager.open(fileName);
        BufferedReader indexBufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder htmlStringBuilder = new StringBuilder();
        String htmlFileString;
        while ((htmlFileString = indexBufferedReader.readLine()) != null) {
            htmlStringBuilder.append(htmlFileString).append('\n');
        }

        return htmlStringBuilder.toString();
    }

}

You can download the source code here.

Happy coding :)

No comments:

Post a Comment