I would like to add a webserver to my android application for uploading small files to the phone.
The user would start the webserver from the phone by hitting a button. He would then see an ip address that can be accessed by any browser from a pc. The website behind this ip address should show a file upload opportunity.
My question is: Is there an open source project similar to my needs? Or how would you recommend doing this?
you can use NanoHttpd link it's very weight android web server that is nicely embbedible..
package .....;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
final StringBuilder buf = new StringBuilder();
for (Entry<Object, Object> kv : header.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
#Override
public void run() {
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, html);
}
}
}
Related
I was creating a application using socket.io in native android application to communicate with websockets Tester. I have tested it using a online WebSocketServer , but each time when trying to check the connection in android device, 'Connection Error` is Logged.
Error : io.socket.engineio.client.EngineIOException: websocket error
java.net.ProtocolException: Expected HTTP 101 response but was '404 Not Found'
onlineTestingPortal link :https://www.piesocket.com/websocket-tester
SocketServerCode:
package com.example.appsocket;
import android.util.Log;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import io.socket.engineio.client.transports.WebSocket;
public class SocketServer {
private Socket mSocket;
private static SocketServer lbInstance = new SocketServer();
public static SocketServer getInstance() {
return lbInstance;
}
public void callSocketServer(){
try {
IO.Options options = new IO.Options();
options.transports = new String[]{ WebSocket.NAME};
mSocket = IO.socket("wss://demo.piesocket.com/v3/channel_123?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV¬ify_self",options);
mSocket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("Connection Error");
}
});
mSocket.connect();
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("SocketServer: connected call back" + args[0].toString());
mSocket.emit("YOUR_TOPIC", "YOUR_DATA_VALUE");
}
});
} catch (URISyntaxException e) {
System.out.println("Exception is : " + e);
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SocketServer.getInstance().callSocketServer();
}
}
Your problem is because of using socket.io library, you don't need socket.io.
In this link, the correct way to connect to ws protocol is mentioned
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have used the https://github.com/NanoHttpd/nanohttpd code for reference.
When i ran my simple android application. I am getting "application not supported" error. While running my android application in eclipse.
My main activity code is :
package com.example.nanoservertest;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Map;
import java.util.Properties;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8085;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// hello = (TextView) findViewById(R.id.hello);
}
#Override
protected void onResume() {
super.onResume();
System.out.println("inside resume");
try {
server = new MyHTTPD();
server.stratServer();
//server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
//Start
public void stratServer(){
ServerRunner.run(MyHTTPD.class);
}
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
String msg = "<html><body><h1>Hello server</h1>\n";
Map<String, String> parms = session.getParms();
if (parms.get("username") == null)
msg +=
"<form action='?' method='get'>\n" +
" <p>Your name: <input type='text' name='username'></p>\n" +
"</form>\n";
else
msg += "<p>Hello, " + parms.get("username") + "!</p>";
msg += "</body></html>\n";
return new NanoHTTPD.Response(msg);
}
}
}
And My Server runner class is
import java.io.IOException;
public class ServerRunner {
public static void run(Class serverClass) {
try {
executeInstance((NanoHTTPD) serverClass.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void executeInstance(NanoHTTPD server) {
try {
server.start();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
System.exit(-1);
}
System.out.println("Server started, Hit Enter to stop.\n");
try {
System.in.read();
} catch (Throwable ignored) {
}
server.stop();
System.out.println("Server stopped.\n");
}
}
I am unable to start my application.
Try to use this library, it seems to respond to your needs:
AndroidAsync
After an exhaustive search on the internet, I managed to assemble a code that sends data to a server socket created in VB.NET.
' Here is my VB.NET code
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
Public Module MainModule
Private TcpListener As New TcpListener(IPAddress.Parse("10.0.0.100"), 11000)
Dim TcpClient As New TcpClient
Dim NetworkStream As NetworkStream
Public Sub Main()
TcpListener.Start()
While (True)
TcpClient = TcpListener.AcceptTcpClient()
NetworkStream = TcpClient.GetStream()
Dim r_byt(TcpClient.ReceiveBufferSize) As Byte
Dim r_byt_size As Integer = NetworkStream.Read(r_byt, 0, TcpClient.ReceiveBufferSize) - 1
Dim data As String = Encoding.ASCII.GetString(r_byt, 0, r_byt_size)
Console.WriteLine(data)
Dim s_byt() As Byte = Encoding.ASCII.GetBytes("testing")
NetworkStream.Write(s_byt, 0, s_byt.Length)
NetworkStream.Flush()
NetworkStream.Close()
TcpClient.Close()
End While
TcpListener.Stop()
End Sub
End Module
// Here is my Android code
package com.javacodegeeks.android.androidsocketclient;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Client extends Activity {
private static final String SERVER_IP = "10.0.0.100";
private static final int SERVER_PORT = 11000;
private Socket socket;
private EditText InputText = null;
private Button ButtonSend = null;
private TextView LabelReceived = null;
private Thread thread = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputText = (EditText)findViewById(R.id.InputText);
ButtonSend = (Button)findViewById(R.id.ButtonSend);
LabelReceived = (TextView)findViewById(R.id.LabelReceived);
thread = new Thread(new ClientThread());
if (thread != null) {
thread.start();
}
ButtonSend.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
if (socket != null) {
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println(InputText.getText().toString());
out.flush();
out.close();
} else {
LabelReceived.setText("socket is null!");
}
} catch (Exception e) {
LabelReceived.setText(e.getMessage());
}
}
});
}
class ClientThread implements Runnable {
public void run() {
try {
InetAddress IAddress = InetAddress.getByName(SERVER_IP);
socket = new Socket(IAddress, SERVER_PORT);
} catch (Exception e) {
socket = null;
}
}
}
}
The two are working, when I press the "send button" it goes to the server, but when I try to do it again nothing is received.
I am trying to use NanoHTTP to serve up an HTML file with help of Android.
Currently i'm able to do display the page. I'm also new to andriod. The issue is not having a clear picture how to refer the images and css for that html file even after i have taken the files with help of AssetManager. Below i provided the entire code. Could somebody help me on this.
Note: Other permission settings are fine like InternetPermission. Only not having an idea how refer the other supported files (css, images, javascript files) for the html.
package com.web;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.*;
import java.util.*;
public class MainActivity extends Activity
{
private WebServer server;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AssetManager assetManager = getAssets();
String imagePath = "fileapp/image";
String cssPath = "fileapp/css";
String files[] = null;
try {
files = assetManager.list(imagePath);
Log.i("Image", files[0]);
Log.w("Image", files[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Image ",e.getMessage());
}
server = new WebServer();
try {
server.start();
} catch(IOException ioe) {
Log.w("Httpd", "The server could not start.");
}
Log.w("Httpd", "Web server initialized.");
}
// DON'T FORGET to stop the server
#Override
public void onDestroy()
{
super.onDestroy();
if (server != null)
server.stop();
}
private class WebServer extends NanoHTTPD {
public WebServer()
{
super(8080);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title>" +
**"<link href=\"../../../fileapp/css/style.css\" rel=\"stylesheet\">" +**
"</head>"
+ "<body>");
msg.append("**<div class=\"jumbotron-sm\"> <img src=\"../../../fileapp/image/logo.png\">**</div>");
msg.append("<div>My Body Content go here......</div>");
msg.append("</body>"
+ "</html>");
return msg.toString();
}
}
}
Kindly let me know in case of any further details.
Thanks advance for your answers.
I tried to get nanohttpd working under android. I have used this example:
package com.example.android_test;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import com.example.android_test.NanoHTTPD.Response.Status;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hello = (TextView) findViewById(R.id.hello);
}
#Override
protected void onResume() {
super.onResume();
TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
textIpaddr.setText("Please access! http://" + formatedIpAddress + ":" + PORT);
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT);
}
#Override
public Response serve(String uri, Method method, Map<String, String> headers,
Map<String, String> parms, Map<String, String> files) {
final StringBuilder buf = new StringBuilder();
for (Entry<String, String> kv : headers.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
#Override
public void run() {
hello.setText(buf);
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(Status.OK, MIME_HTML, html);
}
}
}
When i start the application on my phone the activity shows the proper ip address. I also can ping the shown address. But when i try to access this via a browser the site will not load. In addition the the above shown MainActivity.java i have only added the NanoHTTPD.java file from the nanohttpd project. Any ideas?
Two things come to mind, both are permissions related. Take a look at your android manifest, you'll want two permissions for your app
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
INTERNET, because you're accessing network services, and WRITE_EXTERNAL_STORAGE because when NanoHttpd receives an incoming connection it writes temp files and most / all phones map the "java.io.tmpdir" to point at the SD card.
See if that helps.