-
Audio files.
Hello,
This code is for transferring audio files between client and server. I used mp3 file format. A new mp3 file called B.mp3 is created but with 0 size, I want the file to play music. Please help me.
SERVER code
Code:
import java.net.*;
import java.io.*;
public class server {
public static void main (String [] args ) throws IOException {
ServerSocket server = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = server.accept();
System.out.println("Accepted connection : " + sock);
File myFile = new File ("C:\\Users\\Sarah\\Desktop\\A.mp3");
byte [] myarray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(myarray,0,myarray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(myarray,0,myarray.length);
os.flush();
sock.close();
}
}
}
Client Code
Code:
import java.net.*;
import java.io.*;
public class client{
public static void main (String [] args ) throws IOException {
int filesize=7022316;
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
Socket sock = new Socket("localhost",13267);
System.out.println("Connecting...");
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Sarah\\Documents\\B.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead != 0);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}
}
Thanks,
Sarah
-
run the server, and point FireFox to
localhost:13267
see what happens. This will tell you if the server is okay.
On the client,
while(bytesRead != 0); <--- are sure about the 0 ?
Read up on InputStream.read, and what it returns when the end is reached.
also, put a
System.out.print(bytesRead);
inside the do-while loop and see what happens.