3 Replies - 972 Views - Last Post: 21 July 2015 - 12:37 PM

#1 chocolade   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 20-July 15

How do i add and use nanohhtpd to make my device http server ?

Posted 20 July 2015 - 08:35 PM

I read in many places about many peoples how did it and most of them say it was easy.
I'm using Eclipse and I have a ready working project in java text to speech so if I'm running it it will speech some text on my android device.

This is my code:



package com.example.texttospeechapp;

import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;

import java.util.Locale;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import fi.iki.elonen.NanoHTTPD;


public class MainActivity extends ActionBarActivity implements OnInitListener {

	
	private static final int MY_DATA_CHECK_CODE = 0;
	TextToSpeech mTts;
	
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		
		//tts = new TextToSpeech(this,(OnInitListener) this);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		

		initTTS();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void initTTS() {
	    Intent checkIntent = new Intent();
	    checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
	    startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if(requestCode == MY_DATA_CHECK_CODE) {
	    if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
	    mTts = new TextToSpeech(this, this);
	    } else {
	    Intent installIntent = new Intent();
	    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
	    startActivity(installIntent);
	        }
	    }
	}
	@SuppressWarnings("deprecation")
	public void onInit(int status) {
	    if(status == TextToSpeech.SUCCESS) {
	        int result = mTts.setLanguage(Locale.US);
	                if(result == TextToSpeech.LANG_AVAILABLE
	                   || result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
	                	     mTts.setPitch(1);
	                         mTts.speak("Capture started this is a voice test heheheheheheheeheheh hello", TextToSpeech.QUEUE_FLUSH, null);
	                }
	    }
	}
}



In the nanohhtpd site they say I need to use unix maven to make it work ? I never used unix before.
Then I saw this code there:

http server test code

But I can't figure out what is the package fi.iki.elonen; I don't have it.
Also all the import.org they are not exist.

I also found a site like this that someone made a nanohttpd java file:

nanohhtpd.java

But again it doesn't help me much. I added the file to my eclipse but I can't call it use it from the MainActivity.java
In this file I saw a class public class NanoHTTPD but I can't get it call it work with it in the MainActivity.java

How can I make this nanohttpd to be working on my Eclipse java code so I can make my android device to become http server ? I'm googling for the last few hours nonstop and can't figure out what to do. What is this Maven ? Should I download it ? Where from ? How to use it ? In the nanohttpd site in GitHub they are saying to type in maven:

mvn archetype:generate -DgroupId=com.example -DartifactId=myHellopApp -DinteractiveMode=false
cd myHellopApp


where to type it how why ? I need the java code.

Is This A Good Question/Topic? 0
  • +

Replies To: How do i add and use nanohhtpd to make my device http server ?

#2 chocolade   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 20-July 15

Re: How do i add and use nanohhtpd to make my device http server ?

Posted 20 July 2015 - 10:17 PM

This is the code in java on Eclipse:


    package com.example.webserver;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketException;
    import java.util.Enumeration;
    
    import android.support.v7.app.ActionBarActivity;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.os.Bundle;
    
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    
    
    
    public class MainActivity extends ActionBarActivity {
    
    	
    	 EditText welcomeMsg;
    	 TextView infoIp;
    	 TextView infoMsg;
    	 String msgLog = "";
    	 
    	 ServerSocket httpServerSocket;
    
    	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		
    		welcomeMsg = (EditText) findViewById(R.id.welcomemsg);
    		  infoIp = (TextView) findViewById(R.id.infoip);
    		  infoMsg = (TextView) findViewById(R.id.msg);
    
    		  infoIp.setText(getIpAddress() + ":" 
    		   + HttpServerThread.HttpServerPORT + "\n");
    
    		  HttpServerThread httpServerThread = new HttpServerThread();
    		  httpServerThread.start();
    
    	}
    
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.main, menu);
    		return true;
    	}
    
    	@Override
    	public boolean onOptionsItemSelected(MenuItem item) {
    		// Handle action bar item clicks here. The action bar will
    		// automatically handle clicks on the Home/Up button, so long
    		// as you specify a parent activity in AndroidManifest.xml.
    		int id = item.getItemId();
    		if (id == R.id.action_settings) {
    			return true;
    		}
    		return super.onOptionsItemSelected(item);
    	}
    	
    	@Override
    	 protected void onDestroy() {
    	  super.onDestroy();
    
    	  if (httpServerSocket != null) {
    	   try {
    	    httpServerSocket.close();
    	   } catch (IOException e) {
    	    e.printStackTrace();
    	   }
    	  }
    	 }
    
    	
    	private String getIpAddress() {
    		  String ip = "";
    		  try {
    		   Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
    		     .getNetworkInterfaces();
    		   while (enumNetworkInterfaces.hasMoreElements()) {
    		    NetworkInterface networkInterface = enumNetworkInterfaces
    		      .nextElement();
    		    Enumeration<InetAddress> enumInetAddress = networkInterface
    		      .getInetAddresses();
    		    while (enumInetAddress.hasMoreElements()) {
    		     InetAddress inetAddress = enumInetAddress.nextElement();
    
    		     if (inetAddress.isSiteLocalAddress()) {
    		      ip += "SiteLocalAddress: "
    		        + inetAddress.getHostAddress() + "\n";
    		     }
    
    		    }
    
    		   }
    
    		  } catch (SocketException e) {
    		   // TODO Auto-generated catch block
    		   e.printStackTrace();
    		   ip += "Something Wrong! " + e.toString() + "\n";
    		  }
    
    		  return ip;
    		 }
    
    	
    	private class HttpServerThread extends Thread {
    		  
    		  static final int HttpServerPORT = 8888;
    
    		  @Override
    		  public void run() {
    		   Socket socket = null;
    		   
    		   try {
    		    httpServerSocket = new ServerSocket(HttpServerPORT);
    		    
    		    while(true){
    		     socket = httpServerSocket.accept();
    
    		     HttpResponseThread httpResponseThread = 
    		      new HttpResponseThread(
    		       socket, 
    		       welcomeMsg.getText().toString());
    		     httpResponseThread.start();
    		    }
    		   } catch (IOException e) {
    		    // TODO Auto-generated catch block
    		    e.printStackTrace();
    		   }
    
    		  }
    
    		  
    		 }
    
    	
    	private class HttpResponseThread extends Thread {
    		  
    		  Socket socket;
    		  String h1;
    		  
    		  HttpResponseThread(Socket socket, String msg){
    		   this.socket = socket;
    		   h1 = msg;
    		  }
    		  
    		  @Override
    		  public void run() {
    		   BufferedReader is;
    		   PrintWriter os;
    		   String request;
    		   
    		   
    		   try {
    		    is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		    request = is.readLine();
    		    
    		    os = new PrintWriter(socket.getOutputStream(), true);
    		    
    		    String response = 
    		     "<html><head></head>" +
    		     "<body>" +
    		     "<h1>" + h1 + "</h1>" +
    		     "</body></html>";
    		    
    		    os.print("HTTP/1.0 200" + "\r\n");
    		    os.print("Content type: text/html" + "\r\n");
    		    os.print("Content length: " + response.length() + "\r\n");
    		    os.print("\r\n");
    		    os.print(response + "\r\n");
    		    os.flush();
    		    socket.close();
    		    
    		    
    		    msgLog += "Request of " + request 
    		      + " from " + socket.getInetAddress().toString() + "\n";
    		    MainActivity.this.runOnUiThread(new Runnable() {
    
    		     @Override
    		     public void run() {
    		      
    		      infoMsg.setText(msgLog);
    		     }
    		    });
    		    
    		   } catch (IOException e) {
    		    // TODO Auto-generated catch block
    		    e.printStackTrace();
    		   }
    		   
    		   return;
    		  }
    		 }
    
    		}



When i'm running it on my real device I see thew welcome message but then I see : Something Wrong! java.net.SocketException:8888

I have a router in this case DLINK N600 my pc is connected to the internet through the router.
I also connected now with my android phone device in wifi to the router.

I also added o the router setting to the Setup > Local Network I added static ip for my android device. I added the hardware mac and ip.

The ip is 10.0.0.3

What I want to do is to run the server on my device as a http web server so I will be able later to connect to it with a client for example from the pc.

The problem is that i'm getting this exception on the java.net.SocketException:8888
Was This Post Helpful? 0
  • +
  • -

#3 chocolade   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 20-July 15

Re: How do i add and use nanohhtpd to make my device http server ?

Posted 21 July 2015 - 03:43 AM

I'm using eclipse java and the nanohttpd.

This is where I took the nanohttpd.java module:

[nanohttpd][1]

In the MainActivity.java of my project I added only this:

@Override
    	protected void onstart() {
    		// TODO Auto-generated method stub
    		super.onstart();
    		DebugServer.MyStart();
    	}


Then I added to my project two module files.

NanoHTTPD.java

DebugServer.java

ServerRunner.java

SimpleWebServer.java

WebServerPlugin.java

WebServerPluginfo.java


This is the DebugServer.java code

    package com.example.webserver;
    
    import fi.iki.elonen.NanoHTTPD;
    import fi.iki.elonen.ServerRunner;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class DebugServer extends NanoHTTPD {
        public DebugServer() {
            super(9080);
            //super(80); // lower than 1024 is not allowed..
        }
    
    /*    
        public static void main(String[] args) {
            ServerRunner.run(DebugServer.class);
        }
    */
        public static void MyStart() {
            ServerRunner.run(DebugServer.class);
        }
        
        @Override public Response serve(IHTTPSession session) {
            Map<String, List<String>> decodedQueryParameters =
                decodeParameters(session.getQueryParameterString());
    
            StringBuilder sb = new StringBuilder();
            sb.append("<html>");
            sb.append("<head><title>Debug Server</title></head>");
            sb.append("<body>");
            sb.append("<h1>Debug Server</h1>");
    
            sb.append("<p><blockquote><b>URI</b> = ").append(
                String.valueOf(session.getUri())).append("<br />");
    
            sb.append("<b>Method</b> = ").append(
                String.valueOf(session.getMethod())).append("</blockquote></p>");
    
            sb.append("<h3>Headers</h3><p><blockquote>").
                append(toString(session.getHeaders())).append("</blockquote></p>");
    
            sb.append("<h3>Parms</h3><p><blockquote>").
                append(toString(session.getParms())).append("</blockquote></p>");
    
            sb.append("<h3>Parms (multi values?)</h3><p><blockquote>").
                append(toString(decodedQueryParameters)).append("</blockquote></p>");
    
            try {
                Map<String, String> files = new HashMap<String, String>();
                session.parseBody(files);
                sb.append("<h3>Files</h3><p><blockquote>").
                    append(toString(files)).append("</blockquote></p>");
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            sb.append("</body>");
            sb.append("</html>");
            return new Response(sb.toString());
        }
    
        private String toString(Map<String, ? extends Object> map) {
            if (map.size() == 0) {
                return "";
            }
            return unsortedList(map);
        }
    
        private String unsortedList(Map<String, ? extends Object> map) {
            StringBuilder sb = new StringBuilder();
            sb.append("<ul>");
            for (Map.Entry entry : map.entrySet()) {
                listItem(sb, entry);
            }
            sb.append("</ul>");
            return sb.toString();
        }
    
        private void listItem(StringBuilder sb, Map.Entry entry) {
            sb.append("<li><code><b>").append(entry.getKey()).
                append("</b> = ").append(entry.getValue()).append("</code></li>");
        }
    }



In my project I added some permission to the manifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.webserver"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="21" />
        <uses-permission android:name="android.permission.INTERNET"/>
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>


I added the line:

<uses-permission android:name="android.permission.INTERNET"/>


My android smartphone device is connected with wifi to my router.
In my router settings I added my smartphone android device mac and ip.

The ip in the router of my android device is: 10.0.0.3

Now i'm running the program throught the Eclipse I see on my device for a second a message: Waiting for debugger...Then it's loading a welcome screen and that's it.

Now i'm going to internet explorer and type in the address window:

10.0.0.3:9080/

Or only 10.0.0.3/

In both cases I get:

This page canít be displayed
ēMake sure that the web address 10.0.0.3:9080 is correct.

And it doesn't do anything on my program no effect.

What's wring here ?


[1]: https://github.com/NanoHttpd/nanohttpd
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: How do i add and use nanohhtpd to make my device http server ?

Posted 21 July 2015 - 12:37 PM

Merged related threads. Please keep it at one thread per project.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1