我想在两个 android 设备之间使用 Wi-Fi 热点 IP 地址和 MAC 地址在 Socket 连接上传输文件。我能够传输小于 1 KB 大小但无法发送其他扩展文件和更大大小的文本文件插座。以下是发件人端的代码:-
Socket socket = null;
File file = new File(
Environment.getExternalStorageDirectory(),
"test.mp3");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
socket = new Socket(dstAddress, dstPort);
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
if (socket != null) {
socket.close();
}
final String sentMsg = "File Sent.....";
((Activity)context_con).runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context_con,
sentMsg,
Toast.LENGTH_LONG).show();
}});
}catch (ConnectException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是接收端的代码:-
try {
File file = new File(
Environment.getExternalStorageDirectory(),
"test.mp3");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
final String sentMsg = "File Received...";
Main.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Main.this,
sentMsg,
Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我想传输更大尺寸的文件,如 mp3 文件,但它只在接收器端创建 1Kb 大小的文件,而不是 2.1 MB 的确切大小。请帮助我在这个实现中哪里错了。