Data transfer between two Wifi devices

跟風遠走 提交于 2019-11-30 05:25:36

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

Examples are taken from here.

For the server side (listening side) you need 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 need a socket that connects to the server socket. Please replace "localhost" with the remote Android devices ip-address or 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();
}
anand krish

For data Transfer between 2 devices over the wifi can be done by using "TCP" protocol. Connection 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 faster transmission of data over wifi can be done by using "WifiDirect" which is a "p2p" connection. so that this will transfer the data from one to other device without an Intermediate(Socket). For example, see this link in google developers wifip2p and P2P Connection with Wi-Fi.

Catch a sample in Github WifiDirectFileTransfer

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