The coding given below demonstrates the file transfer between sender and receiver executing on same port. File is read as byte array and written into OutputStream in the sender code. File content is read as bytes from InputStream and stored in a file.
import java.net.*;
import java.io.*;
public class FileSender {
public static void main(String args[]) throws IOException {
//Create socket:
ServerSocket servesock = new ServerSocket(2345);
while(true) {
System.out.println("Waiting…");
Socket sock = servesock.accept();
System.out.println("Accepted Connection…");
//send file:
File myFile = new File("Billiards.mpg");
byte[] mybytearray = new byte [(int)myFile.length()];
System.out.println("Available bytes = "+myFile.length());
FileInputStream fis = new FileInputStream(myFile);
System.out.println("Total available Bytes:" + fis.available());
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending..");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
import java.net.*;
import java.io.*;
public class FileReceiver {
public static void main(String args[]) throws IOException {
int filesize = 6022386;
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
//local host for testing
Socket sock = new Socket("",2345);
System.out.println("Connecting…");
//Receive file:
byte[] mybytearray = new byte[filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("new Billiards.mpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
System.out.println("bytesRead="+bytesRead);
current = bytesRead;
do {
bytesRead = is.read(mybytearray,current,(mybytearray.length-current));
if(bytesRead >= 0)
current+=bytesRead;
}
while(bytesRead >-1);
System.out.println("current="+current);
bos.write(mybytearray,0,current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}
}