How to send a file from server to client?
I have a server and a client which can both send messages to eachother. When I send a request on my client, it sends a message to my server and my server will create a file on it's filesystem and send it to my client line per line.
Client:
socket = new Socket(InetAddress.getByName(address), Integer.parseInt(port));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
writer.println("GD"); // GD stands for get data
Server:
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(port), 0, InetAddress.getByName(address));
socket = serverSocket.accept();
OutputStream writer = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// SNIP - readline happens in a thread etc. Not important
String line = reader.readLine();
if("GD".equals(line)) {
File dataFile = getDataFile();
BufferedReader br = new BufferedReader(new FileReader(dataFile));
String line;
while(null != (line = br.readLine())) {
writer.send("FD;" + line);
// FD stands for file data so my client knows that it's a line from the requested file
}
}
If my file is rather big (let's say several hundred thousands of lines), it means my server needs to send the data line per line. Not to mention that it has to read through the file and use it's memory to store the strings before sending them. It feels very inefficient.
I was wondering if there is a way to send a file from my server to my client without wasting this many resources. Can anyone help me with this?
So in short: Can I send a file from my server to my client without having to stream through my file and send it line per line.