I have a homework assignment to create a simple data transfer mechanism with a client/server TCP socket pair by redirecting standard I/O. I actually have it working, but when I try to transfer large files (say ~5g) the speed slows down dramatically. I am using BufferedInputStream and BufferedOutputStream, and I think that perhaps there is some optimization I can make there. The code for my server is:
private static final int BUF_SIZE = 2047;
public static void main(String[] args) throws IOException{
/*
* Attempt to parse command line arguments.
* @require args[0] is an int
*/
int port = 0;
try {
port = Integer.parseInt(args[0]);
} catch(NumberFormatException e) {
System.err.println("Port must be an integer in range 0 - 65535.");
System.exit(-1);
}
/*
* Bind server socket to specified port number and wait for request.
* @require port >= 0 && port <= 65535
*/
ServerSocket welcomeSocket = null;
welcomeSocket = new ServerSocket(port);
System.out.println("Now listening on port: " + port);
/*
* Accept connection from client socket.
*/
Socket connectionSocket = null;
connectionSocket = welcomeSocket.accept();
System.out.println("Client made connection");
BufferedInputStream input;
BufferedOutputStream output;
if(System.in.available() > 0) {
input = new BufferedInputStream(System.in, BUF_SIZE);
output = new BufferedOutputStream(
connectionSocket.getOutputStream(), BUF_SIZE);
} else {
input = new BufferedInputStream(
connectionSocket.getInputStream(), BUF_SIZE);
output = new BufferedOutputStream(System.out, BUF_SIZE);
}
int place;
while((place = input.read()) != -1)
output.write(place);
input.close();
output.close();
welcomeSocket.close();
connectionSocket.close();
}
The client code is essentially the same. I have tried using different buffer sizes, including the default (by not specifying a buffer size), but they are all running at approximately the same speed. Any pointers on how I can increase my performance?
Thank you for your time!
You’re reading one byte at a time from the buffer. The overhead of calling this method millions of times is rather large.
I would suggest reading more than one byte into a buffer with the other version (and writing the same way):
Example: