My try to do client socket program
server reads file and print it to console and copies it to output file
Server Program:
package SocketProgramming.copy;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerRecieveFile {
public static void main(String[] args) throws IOException {
// TODO Auto-enerated method stub
int filesize = 1022386;
int bytesRead;
int currentTot;
ServerSocket s = new ServerSocket(0);
int port = s.getLocalPort();
ServerSocket serverSocket = new ServerSocket(15123);
while (true) {
Socket socket = serverSocket.accept();
byte[] bytearray = new byte[filesize];
InputStream is = socket.getInputStream();
File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
FileOutputStream fos = new FileOutputStream(copyFileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray, 0, bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot,
(bytearray.length - currentTot));
if (bytesRead >= 0)
currentTot += bytesRead;
} while (bytesRead > -1);
bos.write(bytearray, 0, currentTot);
bos.flush();
bos.close();
socket.close();
}
}
}
Client program:
package SocketProgramming.copy;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSendFile {
public static void main(String[] args) throws UnknownHostException,
IOException {
// final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
ServerSocket s = new ServerSocket(0);
int port = s.getLocalPort();
Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
System.out.println("Accepted connection : " + socket);
File transferFile = new File(FILE_NAME);
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray, 0, bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray, 0, bytearray.length);
BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
String as = "", line = null;
while ((line = r.readLine()) != null) {
as += line + "\n";
// as += line;
}
System.out.print("Input File contains following data: " + as);
os.flush();
fin.close();
bin.close();
os.close();
socket.close();
System.out.println("File transfer complete");
}
}