This code snippet demonstrates a simple console based file transfer. The server listens for incoming connections and can connect to multiple clients. On connecting to the server, the client sends the filesize and filename of the sending file to the server in two separate transmissions. On the third transmission, the client sends the file. The server is made aware of the filesize and the filename and proceeds to receive the file from the client. The filename is supplied as an argument when executing the client from the command-line.
Usage
java Client "PATH_TO_FILE"
Client
import java.net.*;
import java.io.*;
class Client{
public static void main(String args[]){
try {
// Command argument
String fileName = args[0];
Socket skClient = new Socket( "127.0.0.1", 1234);
System.out.println( "Connected to server!!!");
File file = new File(fileName);
FileInputStream fReader = new FileInputStream(file);
OutputStreamWriter sWriter = new OutputStreamWriter(skClient.getOutputStream());
// Send file size to server.
String fileSize = Long.toString(file.length());
sWriter.write(fileSize+ "\n");
sWriter.flush();
// Send filename to server.
sWriter.write(file.getName()+ "\n");
sWriter.flush();
byte[] buffer = new byte[Integer.parseInt(fileSize)];
int bytesRead = 0;
OutputStream oStream = skClient.getOutputStream();
System.out.println( "Sending file to server.");
// Send the file to the server.
while ((bytesRead = fReader.read(buffer))>0)
{
oStream.write(buffer,0,bytesRead);
}
oStream.close();
fReader.close();
skClient.close();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Server
import java.net.*;
import java.io.*;
class Server{
public static void main(String args[]){
System.out.println( "Server started");
try {
ServerSocket skServer = new ServerSocket(1234);
while (true){
Socket skClient = skServer.accept();
InputStreamReader sReader = new InputStreamReader(skClient.getInputStream());
BufferedReader bReader = new BufferedReader(sReader);
// Receive filesize from client
String fileSize = bReader.readLine();
// Receive filename from client
String fileName = bReader.readLine();
System.out.println( "File Size: " + fileSize);
System.out.println( "Filename: " + fileName);
// Create a file in the same location as the running server.
FileOutputStream oStream = new FileOutputStream(new File(fileName));
byte[] buffer = new byte[Integer.parseInt(fileSize)];
int bytesReceived = 0;
InputStream iStream = skClient.getInputStream();
while ((bytesReceived = iStream.read(buffer))>0)
{
/* Write to the file */
oStream.write(buffer,0,bytesReceived);
}
oStream.close();
iStream.close();
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
No comments:
Post a Comment