【问题标题】:Sending data over p2p network in Android在 Android 中通过 p2p 网络发送数据
【发布时间】:2015-05-21 16:44:40
【问题描述】:

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

请帮忙

【问题讨论】:

    标签: android client wifi server p2p


    【解决方案1】:

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

    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
    

    【讨论】:

    • 如果您了解 Java 中的本地套接字编程知识,您应该使用此代码...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    相关资源
    最近更新 更多