在Android

时间:2015-05-21 16:44:41

标签: android client wifi server p2p

我正在Android中进行一些实验,但我无法将数据从一个设备发送到另一个设备。我需要一个p2p网络,这样如果一个设备接收到数据,那么另一个设备也可以从那些已经接收到数据的设备获取数据。 我也研究过并看过有关wifi的视频,但他们只讲述扫描wifi和启动/停止wifi。

请帮忙

1 个答案:

答案 0 :(得分:0)

下面我们有两个Thread类来发送和接收文件......

public class FileRead extends Thread {
        Socket socket;
        String name;

        FileRead(Socket socket,String filename) {
            this.socket=socket;
        this.name=name;
    }

    @Override
    public void run() {
        File file=null;
        try {


            file = new File (filePath,name);

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            byte[] bytes;
            FileOutputStream fos = null;
            try {
                bytes = (byte[])ois.readObject();

                fos = new FileOutputStream(file);
                fos.write(bytes);

            } catch (ClassNotFoundException e) {
                Log.i("INFO","class not found exception");

            }

        } catch (IOException e) {

            e.printStackTrace();
        }

    }
    }


public class FileSend extends Thread {
    Socket socket;
File file;
    FileSend(Socket socket,File f){
        this.socket= socket;
        file=f;
    }

    @Override
    public void run() {



        byte[] bytes = new byte[(int) file.length()];
        BufferedInputStream bis;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bis.read(bytes, 0, bytes.length);

            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(bytes);
            oos.flush();

        } catch (FileNotFoundException e) {
            Log.i("INFO","  file not found exception");

        } catch (IOException e) {
            Log.i("INFO","  io exception exception");
        }
    }

我们使用两个不同设备上的两个绑定套接字之间发送文件。 通过下面的代码启动这些线程

File file = new File(FILEPATH+File.separator+FILENAME);
    FileSend fileSend = new FileSend(socket,file);
    fileSend.start();//write file

    FileRead fileRead =new FileRead(socket,RECIEVEDFILENAME);
    fileRead.start();//read file