How to Broadcast message from Group Owner to all or particular client(s) ? Android Wi-Fi Direct

会有一股神秘感。 提交于 2020-01-05 04:19:08

问题


  • I am developing demo to send and receive data through WIFI DIRECT.
  • It works fine multiple clients are connecting to the owner and all clients can send data and also Group owner receives those all data from clients.
  • I have used wifi direct demo of google.

But the problem is, I am not getting how to send data from Group owner to all or particular client(s).

I tried to do this after storing client's IP but it is not working.

I am searching for this since last two days but haven't got proper solution for this yet.

Is there any way to send data from Group owner to clients?

Calling ServiceIntent

Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
                        serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
                        serviceIntent.putExtra("data" , data1.toString());
                        serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
                               info.groupOwnerAddress.getHostAddress());
                        serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
                        getActivity().startService(serviceIntent);

I have tried by replacing client's IP instead of info.groupOwnerAddress.getHostAddress(). But it says host is unresolved

FileTransferService.java

public class FileTransferService extends IntentService {
    private static final int SOCKET_TIMEOUT = 5000;
    public static final String ACTION_SEND_FILE = "com.wifidatatransfer.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 FileTransferService(String name) {
        super(name);
    }
    public FileTransferService() {
        super("FileTransferService");
    }
    /*
     * (non-Javadoc)
     * @see android.app.IntentService#onHandleIntent(android.content.Intent)
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        Context context = getApplicationContext();
        if (intent.getAction().equals(ACTION_SEND_FILE)) {
            String data = intent.getExtras().getString("data");
            String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
            Socket socket = new Socket();
            int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
            try {
                Log.d(WiFiDirectActivity.TAG, "Opening client socket - "+host+":::::"+port);
                socket.bind(null);
                socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
                Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
                OutputStream stream = socket.getOutputStream();
                String stringToConvert = "This is my data";
                byte[] theByteArray = stringToConvert.getBytes();
                stream.write(theByteArray);
                ContentResolver cr = context.getContentResolver();
                InputStream is = null;


                try {
                     is = new ByteArrayInputStream(data.getBytes());
                } catch (Exception e) {
                    Log.d(WiFiDirectActivity.TAG, e.toString());
                }
                DeviceDetailFragment.copyFile(is, stream);
                Log.d(WiFiDirectActivity.TAG, "Client: Data written");
            } catch (IOException e) {
                Log.e(WiFiDirectActivity.TAG, e.getMessage());
            } finally {
                if (socket != null) {
                    if (socket.isConnected()) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            // Give up
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

FileServerAsyncTask

 public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
        private Context context;
        private TextView statusText;
        private int port;

        /**
         * @param context
         * @param statusText
         */
        public FileServerAsyncTask(Context context, View statusText , int port) {
            this.context = context;
            this.statusText = (TextView) statusText;
            this.port=port;

        }
        @Override
        protected String doInBackground(Void... params) {

            if (info.groupFormed && info.isGroupOwner) {
                try {
                    ServerSocket serverSocket = new ServerSocket(port);


                    Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
                    Socket client = serverSocket.accept();
                    Log.d(WiFiDirectActivity.TAG, "Server: connection done");



                    InputStream inputstream = client.getInputStream();
                    String gotData = convertStreamToString(inputstream);
                    Log.d(WiFiDirectActivity.TAG, "server: copying files " + gotData);



                    return gotData;
                } catch (IOException e) {
                    Log.e(WiFiDirectActivity.TAG, e.getMessage());
                    return null;
                }

            }else{
                try {
                    ServerSocket serverSocket = new ServerSocket(port);

                    Socket ss= serverSocket.accept();
                    OutputStream os= ss.getOutputStream();

                   return os.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                    return  null;
                }
            }
        }


        /*
         * (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(String result) {
            if (result != null) {


                statusText.setText("File copied - " + result);

                Toast.makeText(context , "Result is:::::"+result, Toast.LENGTH_LONG).show();

            }
        }

onConnectionInfoAvailable(()

 @Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        System.out.println("CONNECTION INFO AVAILABLE:::::::::;Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
    this.info = info;





    this.getView().setVisibility(View.VISIBLE);
    // The owner IP is now known.
    TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
    view.setText(getResources().getString(R.string.group_owner_text)
            + ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
                    : getResources().getString(R.string.no)));
    // InetAddress from WifiP2pInfo struct.
    view = (TextView) mContentView.findViewById(R.id.device_info);
    System.out.println("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
    view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
    // After the group negotiation, we assign the group owner as the file
    // server. The file server is single threaded, single connection server
    // socket.
    if (info.groupFormed && info.isGroupOwner) {
        new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text),8988)
                .execute();
        mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);

    } else if (info.groupFormed) {
        // The other device acts as the client. In this case, we enable the
        // get file button.
        clientIP=info.groupOwnerAddress.getHostAddress();


        mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
        ((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
                .getString(R.string.client_text));
    }
    // hide the connect button
    mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}

来源:https://stackoverflow.com/questions/39589868/how-to-broadcast-message-from-group-owner-to-all-or-particular-clients-andro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!