3

I am trying to write an android application that streams images taken from a first device, through the camera, to a second device with WiFi Direct.

I am trying to use this GitHub project, WiFiDIrectDemo, I managed to connect the devices and to send just one file. When I try to send a second file I don't get any error and, from the logs, everything seems to work, but the second device doesn't get any file.

Is this a known issue? I have tried to look on the internet but I could not find anything that could help me.

I am attaching my File Transfer Service class:

public class FileTransferService extends IntentService {

Handler mHandler;

public static final int SOCKET_TIMEOUT = 50000; //ms
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";

public static  int PORT = 8888;
public static final String inetaddress = "inetaddress";
public static final int ByteSize = 512;
public static final String Extension = "extension";
public static final String Filelength = "filelength";
public FileTransferService(String name) {
    super(name);
}

public FileTransferService() {
    super("FileTransferService");
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    mHandler = new Handler();
}

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    if (intent.getAction().equals(ACTION_SEND_FILE)) {
        String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);

        String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);

        Socket socket = new Socket();

        InputStream is = null;

        int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);

        String extension = intent.getExtras().getString(Extension);

        String filelength = intent.getExtras().getString(Filelength);


        try {
            if(!socket.isConnected())
            {
                Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
                socket.bind(null);

                socket.setReuseAddress(true);

                socket.connect((new InetSocketAddress(host, port)),5000); // ..,socket_timeout)
                Log.e("File Transfer Service"," socket connect");

            }

            Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());

            OutputStream stream = socket.getOutputStream();
            Log.e("file transfer" +
                    " service", "get output stream");
            ContentResolver cr = context.getContentResolver();


            Long FileLength = Long.parseLong(filelength);
            WiFiTransferModal transObj = null;
            ObjectOutputStream oos = new ObjectOutputStream(stream);
            if(transObj == null) transObj = new WiFiTransferModal();


            transObj = new WiFiTransferModal(extension,FileLength);
            oos.writeObject(transObj);

            try {
                is = cr.openInputStream(Uri.parse(fileUri));
            } catch (FileNotFoundException e) {
                Log.d(WiFiDirectActivity.TAG, e.toString());
            }
            DeviceDetailFragment.copyFile(is, stream);
            Log.d(WiFiDirectActivity.TAG, "Client: Data written");
            oos.flush();
            oos.close();    //close the ObjectOutputStream after sending data.
        } catch (IOException e) {
            Log.e("file transfer service","unable to connect:  " + e.toString() );
        } finally {
            if (socket != null) {
                if (socket.isConnected()) {
                    try {
                        socket.close();

                    } catch (Exception e) {
                        // Give up
                        e.printStackTrace();
                        Log.e("File transfer service","exception socket.close:  " + e.toString());
                    }
                }
            }
            else Log.e("file transfer service","socket is already null");
        }

    }
}
}

EDIT

Receiving code:

 public class FileServerAsyncTask extends AsyncTask<String, String, String> {

    //        private TextView statusText;
    private Context mFilecontext;
    private String Extension, Key;
    private File EncryptedFile;
    private long ReceivedFileLength;
    private int PORT;

    public FileServerAsyncTask(Context context, int port) {
        this.mFilecontext = context;
        handler = new Handler();
        this.PORT = port;

    }


    @Override
    protected String doInBackground(String... params) {
        try {
            Log.e("device detail fragment", "File Async task port-> " + PORT);

            ServerSocket serverSocket = new ServerSocket();
            Log.e("device detail fragment"," new server");

            serverSocket.setReuseAddress(true);
            Log.e("device detail fragment","set reuse address");

            serverSocket.bind(new InetSocketAddress(PORT));
            Log.e("device detail fragment","socket bind");

            Socket client = serverSocket.accept();
            Log.e("device detail fragment "," socket client accept");

            Log.e("Device detail fragment ", "client inet address" + client.getInetAddress());

            WiFiClientIp = client.getInetAddress().getHostAddress();
            Log.e("device detail fragment"," get client ip: " + WiFiClientIp);

            ObjectInputStream ois = new ObjectInputStream(
                    client.getInputStream());
            Log.e("device detail fragment","object input stream + " + ois.toString());

            WiFiTransferModal obj = null;
            String InetAddress;

            try {
                obj = (WiFiTransferModal) ois.readObject();
                Log.e("device detail fragment"," read object");

                if (obj != null) {
                    Log.e("device detail fragment"," obj != null ");
                    InetAddress = obj.getInetAddress();
                    Log.e("device detail fragment"," get inet address: " +
                    InetAddress);
                    if (InetAddress != null
                            && InetAddress
                            .equalsIgnoreCase(FileTransferService.inetaddress)) {

                        SharedPreferencesHandler.setStringValues(mFilecontext,
                                mFilecontext.getString(R.string.pref_WiFiClientIp), WiFiClientIp);


                        //set boolean true which identify that this device will act as server.
                        SharedPreferencesHandler.setStringValues(mFilecontext,
                                mFilecontext.getString(R.string.pref_ServerBoolean), "true");

                        ois.close(); // close the ObjectOutputStream object
                        Log.e("device detail fragment"," output stream close");
                        // after saving
                        serverSocket.close();
                        Log.e("device detail fragment","close");
                        return "Demo";
                    }

                    Log.e("device detail fragment","FileName got from socket on other side->>> "+
                            obj.getFileName());
                }

                final File f = new File(
                        Environment.getExternalStorageDirectory() + "/"
                                + FolderName + "/"
                                + obj.getFileName());
                Log.e("background"," new file f from inputstream");

                File dirs = new File(f.getParent());
                Log.e("device detail fragment"," f get parent()");
                if (!dirs.exists())
                    dirs.mkdirs();
                f.createNewFile();
                Log.e("device detail fragment","create new file");

            /**
             * Receive file length and copy after it
             */
                this.ReceivedFileLength = obj.getFileLength();

                InputStream inputstream = client.getInputStream();
                Log.e("device detail fragment","input stream client get input");
                Message msg = Message.obtain();
                msg.what = 1;
                try
                {
                    // send the images to the image view through handler
                    Bitmap bitmap = BitmapFactory.decodeStream(inputstream);
                    Log.e("device detail fragment", "decode stream");
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);
                    msg.setData(b);
                    Log.e("device detail fragment","message: " + msg.toString());
                    messageHandler.sendMessage(msg);
                }
                catch (Exception e)
                {
                    Log.e("device detail fragment","stream not decoded into bitmap with" +
                    "exception:   " + e.toString());
                }

                copyRecievedFile(inputstream, new FileOutputStream(f),
                        ReceivedFileLength);
                Log.e("device detail fragment","copy input stream into file");
                ois.close(); // close the ObjectOutputStream object after saving
                // file to storage.
                Log.e("device detail fragment","ois close");

                /**
                 *  Set file related data and decrypt file in postExecute.
                 *  */
                this.Extension = obj.getFileName();
                this.EncryptedFile = f;
                final Uri uri = Uri.fromFile(f);
                return f.getAbsolutePath();
            }
            catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
                Log.e("device detail fragment", e.getMessage());
            }

            return "";
        } catch (IOException e) {
            Log.e("device detail fragment", e.getMessage());
            return null;
        }
    }


    @Override
    protected void onPostExecute(String result) {

        if (result != null) {
            if (!result.equalsIgnoreCase("Demo")) {
                Log.e("On Post Execute","result  +" + result);
            } else if (!TextUtils.isEmpty(result)) {
                /**
                 * To initiate socket again we are initiating async task
                 * in this condition.
                 */
                FileServerAsyncTask FileServerobj = new
                        FileServerAsyncTask(mFilecontext, FileTransferService.PORT);
                if (FileServerobj != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        FileServerobj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
                        Log.e("Post Execute", "FileServerobj.execute on executor");

                    } else
                        {
                            FileServerobj.execute();
                            Log.e("Post Execute", "FileServerobj.execute");
                        }
                }
            }
        }

    }

    @Override
    protected void onPreExecute() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(mFilecontext);
        }
        if(imageView == null){
            imageView = new ImageView(mFilecontext);
        }
    }
}
Matteo Peluso
  • 452
  • 1
  • 6
  • 23
  • There are a lot of things in the code you posted that i do not understand. But if the receiver does not receive the second file then it would not be bad to see the code you use on receiving side. – greenapps Nov 16 '17 at 09:50
  • Thanks for the answer, I'm sorry I didn't wrote a complete question.I'm going to edit the question and put also the receiving side. – Matteo Peluso Nov 16 '17 at 10:01
  • Post only the server asynctask. Not a complete activity or fragment. – greenapps Nov 16 '17 at 10:28
  • The server will receive a file and then opens it by letting the user choose an app to display the file. Can you confirm this? The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour. – greenapps Nov 16 '17 at 10:34
  • At the beginning the server received a file and then open it with another function, I have changed the code so that, now, the received file, that should be an image, is handled to an image view. You are suggesting me that I am using this task in a wrong way? I so should modify it so that it doesn't end the connection and the end ? – Matteo Peluso Nov 16 '17 at 10:37
  • `* To initiate socket again we are initiating async task * in this condition.`. Your code is not coming there. Can you check and confirm? – greenapps Nov 16 '17 at 10:37
  • yes, it wasn't going there, that's the reason why I could send just one file or is another error? – Matteo Peluso Nov 16 '17 at 11:03

1 Answers1

0

The server will receive a file and then opens it by letting the user choose an app to display the file. The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour.

* To initiate socket again we are initiating async task * in this condition.. 

Your code is not coming there.

You have to start an asynctask again to receive the next file.

greenapps
  • 11,154
  • 2
  • 16
  • 19