[英]Sending data over p2p network in Android
我正在Android上進行一些實驗,但無法將數據從一台設備發送到另一台設備。 我需要一個p2p網絡,以便如果一個設備接收到數據,則另一台設備可以從那些已經接收到數據的設備中獲取數據。 我也研究和觀看了有關wifi的視頻,但它們僅講述掃描wifi和開始/停止wifi的過程。
請幫忙
下面我們有兩個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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.