This program downloads a mp3 file from server to client using TCP socket connection. AudioFile is a user defined class.
Client Side Code
public void downloadAudio(AudioFile a) {
File myDir = null;
try {
myDir = new File("Downloads");
myDir.mkdir();
getConnection();
oos = new ObjectOutputStream(soc.getOutputStream());
oos.writeObject(a);
in = new BufferedInputStream(soc.getInputStream());
File f = new File("Downloads/" + a.getTrackName() + ".mp3");
out = new FileOutputStream(f);
int i = 0;
downloaded = 0;
byte[] bytesIn = new byte[1024];
while ((i = in.read(bytesIn)) >= 0) {
out.write(bytesIn, 0, i);
downloaded += bytesIn.length;
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
}
}
Server Side Code
private void download(File file) {
try {
out = new BufferedOutputStream(soc.getOutputStream());
in = new FileInputStream(file);
int i = 0;
byte[] bytesIn = new byte[1024];
while ((i = in.read(bytesIn)) >= 0) {
out.write(bytesIn, 0, i);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
No comments:
Post a Comment