[ACCEPTED]-Data transfer between two Wifi devices-android-wifi

Accepted answer
Score: 19

To send data in a meaningful manner between 10 two Android devices you would use a TCP 9 connection. To do that you need the ip address 8 and the port on which the other device is 7 listening.

Examples are taken from here.

For 6 the server side (listening side) you need 5 a server socket:

try {
        Boolean end = false;
        ServerSocket ss = new ServerSocket(12345);
        while(!end){
                //Server is waiting for client here, if needed
                Socket s = ss.accept();
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
                String st = input.readLine();
                Log.d("Tcp Example", "From client: "+st);
                output.println("Good bye and thanks for all the fish :)");
                s.close();
                if ( STOPPING conditions){ end = true; }
        }
ss.close();


} catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
} catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}

For the client side you 4 need a socket that connects to the server 3 socket. Please replace "localhost" with 2 the remote Android devices ip-address or 1 hostname:

try {
        Socket s = new Socket("localhost",12345);

        //outgoing stream redirect to socket
        OutputStream out = s.getOutputStream();

        PrintWriter output = new PrintWriter(out);
        output.println("Hello Android!");
        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));

        //read line(s)
        String st = input.readLine();
        //. . .
        //Close connection
        s.close();


} catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
} catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}
Score: 3

For data Transfer between 2 devices over 9 the wifi can be done by using "TCP" protocol. Connection 8 between Client and Server requires 3 things

  1. Using NSD Manager, Client device should get server/host IP Address.
  2. Send data to server using Socket.
  3. Client should send its IP Address to server/host for bi-directional communication.

For 7 faster transmission of data over wifi can 6 be done by using "WifiDirect" which 5 is a "p2p" connection. so that 4 this will transfer the data from one to 3 other device without an Intermediate(Socket). For 2 example, see this link in google developers 1 wifip2p and P2P Connection with Wi-Fi.

Catch a sample in Github WifiDirectFileTransfer

More Related questions