I am trying to make a server which receives some big files sent by the client and create the same file on an another location (basically download that file and move it in another place). The problem is that the servers freeze when trying to send big files. Server.java:
package testing_server;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException
{
ServerSocket server = new ServerSocket(2000);
Client client2 = new Client();
client2.main("");
while (true)
{
Socket client = server.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
int a;
byte[] buffer = new byte[1025];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((a= in.read(buffer))!=-1 )
{
bos.write(buffer,0,a);
bos.flush();
System.err.println(a);
}
}
}
}
And this is Client.java
package testing_server;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Iterator;
public class Client {
public static void main(String args) throws UnknownHostException, IOException, InterruptedException
{
Socket server = new Socket("ip",2000);
DataOutputStream out = new DataOutputStream(server.getOutputStream());
final FileChannel channel = new FileInputStream("test.jpg").getChannel();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
byte[] ar = new byte[1025];
//this is only for testing
int many = buffer.capacity()/1025;
int i =0;
while (i<=many)
{
buffer.get(ar);
out.write(ar,0,1025);
out.flush();
i++;
}
// when finished
channel.close();
out.close();
server.close();
}
}
How can I send this big file without freeze. And can I send it in only one piece so I won't lose bytes? And if not how can i somehow manage to not lose bytes while sending chunks? I mention that the file is 10MB so it is not a very large file. I want to manage this without compression.