Android FTP服务器 [英] Android FTP Server

查看:94
本文介绍了Android FTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码以使android设备成为ftp服务器(Android内部存储).我遇到了os.android.NetworkOnMainThread的异常.我试图将onStart代码放在AsyncTask中,但是应用程序从不执行,并且在启动时崩溃.关于Android上ftp服务器的任何帮助将非常有用,因为我不知道如何使它正常工作.

这是MainActivity代码

package com.googlecode.simpleftp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;


public class FTPServer extends Activity {
    private static int COMMAND_PORT = 2121;
    static final int DIALOG_ALERT_ID = 0;
    private static ExecutorService executor  = Executors.newCachedThreadPool();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.my_menu, menu);
            return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    
            // Handle item selection    
            switch (item.getItemId()) {
                    case R.id.new_game:    
                            System.out.println("New game button is pressed!");
                            //newGame();        
                            return true;    
                    case R.id.quit:        
                            System.out.println("Quit button is pressed!");
                            showDialog(DIALOG_ALERT_ID);        
                            return true;    
                    default:        
                            return super.onOptionsItemSelected(item);    }
    }

    @Override
    protected Dialog onCreateDialog(int id){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure you want to exit?")
            .setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int id){
                            FTPServer.this.finish();
                    }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                    }
            });
            AlertDialog alert = builder.create();
            return alert;
    }

这是ServerPI代码

 import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.PrintWriter;
 import java.net.Socket;

 public class ServerPI implements Runnable{
    private Socket clientSocket;
    private BufferedReader in;
    private PrintWriter out;

    private String baseDir;
    private String relativeDir;
    private String absoluteDir;
    private String fileName;
    private String filePath;

    public ServerPI(Socket incoming) throws IOException{
            this.clientSocket = incoming;
            in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            out = new PrintWriter(this.clientSocket.getOutputStream(), true);

            baseDir = new File("").getAbsolutePath();

            relativeDir = "/";
            absoluteDir = baseDir + relativeDir;
            fileName = "";
            filePath = absoluteDir + "/" + fileName;
    }

    private void readCommandLoop() throws IOException {
            String line = null;
            reply(220, "Welcome to the SimpleFTP server!");
            while((line = in.readLine()) != null){
                    int replyCode = executeCommand(line.trim());
                    if(replyCode == 221){
                            return;
                    }
            }
    }

    private int executeCommand(String trim) {
            // TODO Auto-generated method stub
            return 0;
    }

    public int reply(int statusCode, String statusMessage){
            out.println(statusCode + " " + statusMessage);
            return statusCode;
    }

    @Override
    public void run(){
            try{
                    this.readCommandLoop();
            } catch (IOException e){
                    e.printStackTrace();
            }
            finally {
                    try {
                            if(in != null){
                                    in.close();
                                    in = null;
                            }
                            if(out != null){
                                    out.close();
                                    out = null;
                            }
                            if (clientSocket != null){
                                    clientSocket.close();
                                    clientSocket = null;
                            }
                    }
                    catch (IOException e){
                            e.printStackTrace();
                    }
            }
    }
    }

我已将代码放在AsyncTask中,在这里

   private class LongOperation extends AsyncTask<String, Void, String> {

      @Override
      protected String doInBackground(String... params) {
           ServerSocket s = null;
    Socket incoming = null;

    try{
            s = new ServerSocket(COMMAND_PORT);
            String ip = (s.getInetAddress()).getHostAddress();
            Context context = this.getApplicationContext();
            CharSequence text = ip;
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, duration);
            Thread.sleep(1000);
            toast.show();
            while(true){
                    incoming = s.accept();
                    executor.execute(new ServerPI(incoming));
            }
    }
    catch(Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
    }
    finally{
            try
                    {
                            if(incoming != null)incoming.close();
                    }
                    catch(IOException ignore)
                    {
                            //ignore
                    }

                    try
                    {
                            if (s!= null)
                            {
                                    s.close();
                            }
                    }
                    catch(IOException ignore)
                    {
                            //ignore
                    }
    }

            return "Executed";
      }      

      @Override
      protected void onPostExecute(String result) {               
      }

      @Override
      protected void onPreExecute() {
      }

      @Override
      protected void onProgressUpdate(Void... values) {
      }
}

我在onCreate方法中调用longOpertation.该应用在启动时崩溃的问题是什么.

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_fullscreen);
            new LongOperation().execute();
    }

解决方案

在我的应用程序中使用Swiftp应用程序(开源)作为服务有助于我完成任务.谢谢大家的帮助.如果有人要关注,请点击链接.

I am using the following code to make the android device a ftp server (Android Internal storage). I am getting the exception of os.android.NetworkOnMainThread. I have tried to put the onStart code in the AsyncTask but app never executes and crashes on launch. Any help regarding the ftp server on Android will be great as i have no idea how to get it working.

Here is the MainActivity Code

package com.googlecode.simpleftp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;


public class FTPServer extends Activity {
    private static int COMMAND_PORT = 2121;
    static final int DIALOG_ALERT_ID = 0;
    private static ExecutorService executor  = Executors.newCachedThreadPool();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.my_menu, menu);
            return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    
            // Handle item selection    
            switch (item.getItemId()) {
                    case R.id.new_game:    
                            System.out.println("New game button is pressed!");
                            //newGame();        
                            return true;    
                    case R.id.quit:        
                            System.out.println("Quit button is pressed!");
                            showDialog(DIALOG_ALERT_ID);        
                            return true;    
                    default:        
                            return super.onOptionsItemSelected(item);    }
    }

    @Override
    protected Dialog onCreateDialog(int id){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure you want to exit?")
            .setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int id){
                            FTPServer.this.finish();
                    }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                    }
            });
            AlertDialog alert = builder.create();
            return alert;
    }

HEre is the ServerPI Code

 import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.PrintWriter;
 import java.net.Socket;

 public class ServerPI implements Runnable{
    private Socket clientSocket;
    private BufferedReader in;
    private PrintWriter out;

    private String baseDir;
    private String relativeDir;
    private String absoluteDir;
    private String fileName;
    private String filePath;

    public ServerPI(Socket incoming) throws IOException{
            this.clientSocket = incoming;
            in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            out = new PrintWriter(this.clientSocket.getOutputStream(), true);

            baseDir = new File("").getAbsolutePath();

            relativeDir = "/";
            absoluteDir = baseDir + relativeDir;
            fileName = "";
            filePath = absoluteDir + "/" + fileName;
    }

    private void readCommandLoop() throws IOException {
            String line = null;
            reply(220, "Welcome to the SimpleFTP server!");
            while((line = in.readLine()) != null){
                    int replyCode = executeCommand(line.trim());
                    if(replyCode == 221){
                            return;
                    }
            }
    }

    private int executeCommand(String trim) {
            // TODO Auto-generated method stub
            return 0;
    }

    public int reply(int statusCode, String statusMessage){
            out.println(statusCode + " " + statusMessage);
            return statusCode;
    }

    @Override
    public void run(){
            try{
                    this.readCommandLoop();
            } catch (IOException e){
                    e.printStackTrace();
            }
            finally {
                    try {
                            if(in != null){
                                    in.close();
                                    in = null;
                            }
                            if(out != null){
                                    out.close();
                                    out = null;
                            }
                            if (clientSocket != null){
                                    clientSocket.close();
                                    clientSocket = null;
                            }
                    }
                    catch (IOException e){
                            e.printStackTrace();
                    }
            }
    }
    }

I have put the code in the AsyncTask, here it is

   private class LongOperation extends AsyncTask<String, Void, String> {

      @Override
      protected String doInBackground(String... params) {
           ServerSocket s = null;
    Socket incoming = null;

    try{
            s = new ServerSocket(COMMAND_PORT);
            String ip = (s.getInetAddress()).getHostAddress();
            Context context = this.getApplicationContext();
            CharSequence text = ip;
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, duration);
            Thread.sleep(1000);
            toast.show();
            while(true){
                    incoming = s.accept();
                    executor.execute(new ServerPI(incoming));
            }
    }
    catch(Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
    }
    finally{
            try
                    {
                            if(incoming != null)incoming.close();
                    }
                    catch(IOException ignore)
                    {
                            //ignore
                    }

                    try
                    {
                            if (s!= null)
                            {
                                    s.close();
                            }
                    }
                    catch(IOException ignore)
                    {
                            //ignore
                    }
    }

            return "Executed";
      }      

      @Override
      protected void onPostExecute(String result) {               
      }

      @Override
      protected void onPreExecute() {
      }

      @Override
      protected void onProgressUpdate(Void... values) {
      }
}

Iam calling the longOpertation in onCreate method. What is the problem that the app crashes on launch.

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_fullscreen);
            new LongOperation().execute();
    }

解决方案

Using the Swiftp application (open source) as a service in my application helped me to acheive my task. Thanks for everyones help. Here is the link if someone wants to follow

这篇关于Android FTP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆