Java Socket - Upload multiple files using AsyncTask in Android - java

How do I send multiple files especially image file and a special string from android as a client socket to a java server socket?
The file is described in a string array where the string is the path where the files are stored.
As for a special string, it will be used as the parent directory on the server, and the uploaded file will be placed there.
I've try a lot of tutorial in SO,ex Stackoverflow
Here's the skeleton I've made.
Updated
I have succesfully transfer those files, but I cannot passed the special strings parent
Android Client
private void handlingUpload(String vehicleNumber) {
System.out.println("PathImage: " + vehicleNumber);
ArrayList<String> list = new ArrayList<String>();
// Get all path each object and sign into list
for (Image image : images) {
list.add(image.getPath());
}
// just prove if list is not emtpty
for (String temp : list) {
System.out.println("FilePath" + temp);
}
// The rules is sending a String vehicleNumber as parent folder
// element in list uploaded Async
Client client = new Client("192.168.8.34", 59090, vehicleNumber);
client.execute();
}
Class to Handle Android Socket
package com.tsurumaru.dzil.clientwarehouse.controllers;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Client extends AsyncTask<Void, Void, Void> {
private String address;
private int port;
private String textResponse;
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
OutputStream os = null;
DataOutputStream dos = null;
Context context;
ArrayList<String> list;
public Client(Context context, String address, int port, ArrayList<String> list, String textResponse) {
this.context = context;
this.address = address;
this.port = port;
this.textResponse = textResponse;
this.list = list;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(address, port);
//Execute them
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
//write the number of files to the server
dos.writeInt(list.size());
System.out.println("Do In Background TO Server" + list.size());
dos.flush();
//write file names to the server
for (String temp : list) {
dos.writeUTF(temp);
dos.flush();
}
// write file size to the server
int n = 0;
byte[]buf = new byte[4092];
for (String temp : list) {
File file = new File(temp);
dos.writeLong(file.length());
dos.flush();
}
// write the file
for (String temp : list) {
File file = new File(temp);
FileInputStream fis = new FileInputStream(file);
while ((n = fis.read(buf)) != -1) {
dos.write(buf, 0, n);
dos.flush();
}
}
dos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute() {
Log.i("ThreadPost", "onPost");
}
}
Java Server
public class MainWindow extends javax.swing.JFrame {
public static void main(String args[]) {
// Create a Socket Server
Thread starter = new Thread(new ServerStart());
starter.start();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
public class ServerStart implements Runnable {
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(59090);
while (true) {
Socket clientSocket = null;
clientSocket = serverSocket.accept();
// create each thread
Thread listener = new Thread(new ClientHandler(clientSocket));
listener.start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public class ClientHandler implements Runnable {
Socket socket;
public ClientHandler(Socket clientSocket) {
try {
socket = clientSocket;
} catch (Exception ex) {
textAreaLog.append(ex.getMessage());
}
}
#Override
public void run() {
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//read the number of files from the client
int number = dis.readInt();
textAreaLog.append("Number of Files to be received: " + number + "\n");
ArrayList<File> files = new ArrayList<File>(number);
ArrayList<Long> size = new ArrayList<Long>(number);
//read file names, add files to arraylist
for (int i = 0; i < number; i++) {
File file = new File(dis.readUTF());
files.add(file);
}
long longSize;
for (int i = 0; i < number; i++) {
longSize = dis.readLong();
size.add(longSize);
}
int n = 0;
byte[] buf = new byte[4092];
for (int i = 0; i < files.size(); i++) {
long fileSize = size.get(i);
textAreaLog.append("Receiving file: " + files.get(i).getPath() + " size: " + fileSize + "\n");
//read file
try (
//create a new fileoutputstream for each new file
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Server Warehouse\\incoming_lokal\\" + files.get(i).getName())) {
//read file
while (fileSize > 0 && (n = dis.read(buf, 0, (int) Math.min(buf.length, fileSize))) != -1) {
fileOutputStream.write(buf, 0, n);
fileSize -= n;
}
fileOutputStream.close();
}
}
} catch (IOException ex) {
textAreaLog.append(ex.getMessage());
} finally {
textAreaLog.append("Thread Is Done " + "\n");
}
}
}
}
Any help it's so appreciated.

Related

File upload on primary location and same time reading & writing same file to multiple secondary locations

i need to achieve the task as below:-
1). File upload on primary location:-
I want to read from a file and write it to primary location(remote file server).
2). File upload on multiple secondary locations:-
Same time while writing to primary location is running, parallelly
I want to read some chunks of bytes from primary location file
and writing it to multiple secondary location.
I have tried a below program for above approach:-
BufferedInputStream bin = null;
ReadableByteChannel channel = null;
int bufferSize = 1048576;
int readBufferSize = 1024*4;
java.nio.ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(readBufferSize);
InputStream is = new FileInputStream(new File("D:\\Harisingh\\300MB.txt"));
bin = new BufferedInputStream(is,bufferSize);
channel = Channels.newChannel(bin);
int retryCnt = 0;
ByteArrayOutputStream baOS = new ByteArrayOutputStream(bufferSize);
int totalBytes=0;
int itrCount=0;
int maxIterateCnt = 1;
int len;
//primary location writing
SmbFile smbFile = new SmbFile("smb://user:Password#fileserver1ind1.hqdev.india/data/Harisingh/collab_4_1_4/primary.txt");
BufferedOutputStream bFout = new BufferedOutputStream(new SmbFileOutputStream(smbFile));
SmbFileInputStream fis = new SmbFileInputStream("smb://user:Password#fileserver1ind1.hqdev.india/data/Harisingh/collab_4_1_4/primary.txt");
BufferedInputStream binPrimary = new BufferedInputStream(fis);
SmbFileOutputStream secLocation1= new SmbFileOutputStream(new SmbFile("smb://user:Password#fileserver1ind1.hqdev.india/data/Harisingh/collab_4_1_4/Secondary1.txt"));
SmbFileOutputStream secLocation2 = new SmbFileOutputStream(new SmbFile("smb://user:Password#fileserver1ind1.hqdev.india/data/Harisingh/collab_4_1_4/Secondary2.txt"));
SmbFileOutputStream secLocation3 = new SmbFileOutputStream(new SmbFile("smb://user:Password#fileserver1ind1.hqdev.india/data/Harisingh/Secondary/Secondary3.txt"));
try {
if(bufferSize > readBufferSize){
maxIterateCnt = bufferSize/readBufferSize;
}
while((len=channel.read(byteBuffer))>=0)
{
itrCount++;
totalBytes+=len;
baOS.write(byteBuffer.array(),0,len);
if(itrCount>=maxIterateCnt)
{
//primary location writing
try{
bFout.write(baOS.toByteArray(),0,totalBytes);
}catch(Exception se)
{
}
// secondary location writing
new Thread(){
public void run(){
System.out.println("Thread Running");
try {
int count;
byte[] readByteArray = new byte[1024*4];
while ((count = binPrimary.read(readByteArray)) != -1)
{
secLocation1.write(readByteArray, 0, count);
secLocation2.write(readByteArray, 0, count);
secLocation3.write(readByteArray, 0, count);
readByteArray = new byte[1024*4];
count= 0;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
totalBytes=0;
baOS.reset();
itrCount=0;
}
byteBuffer.clear();
}
//primary location writing
try{
bFout.write(baOS.toByteArray(),0,totalBytes);
}catch(Exception se)
{
}
bFout.flush();
bFout.close();
int count;
// secondary location writing
new Thread(){
public void run(){
System.out.println("Thread Running");
try {
int count;
byte[] readByteArray = new byte[1024*4];
while ((count = binPrimary.read(readByteArray)) != -1)
{
secLocation1.write(readByteArray, 0, count);
secLocation2.write(readByteArray, 0, count);
secLocation3.write(readByteArray, 0, count);
readByteArray = new byte[1024*4];
count= 0;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
Now with above program, it writes a file to primary location by main thread and secondary location writing is running in separate thread but i am facing the problem of some bytes writing missing on some secondary locations due to multi threading.
FYI
This question is related to io stream only. It is not specific to JCIFS so you can use same program with simple io stream, don't require smb io stream.
Can you please help me to sort out this?
Here is an example which I do not encourage to use "as is" - it's intention is to act as Proof Of Concept. In example the primary process is done first to achieve best performance for this phase. Then the secondaries are done each in own Thread parallel.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
public class testSmb {
static boolean append = true;
static int threadCount = 0;
static int bufferSize = 2048;
static NtlmPasswordAuthentication auth;
static File localFile;
static SmbFile primarySmbFile;
static BufferedInputStream input;
static SmbFileOutputStream output;
static SmbFile secondary1SmbFile;
static BufferedInputStream sec1Input;
static SmbFileOutputStream sec1Output;
static SmbFile secondary2SmbFile;
static BufferedInputStream sec2Input;
static SmbFileOutputStream sec2Output;
static SmbFile secondary3SmbFile;
static BufferedInputStream sec3Input;
static SmbFileOutputStream sec3Output;
public static Object lock = new Object();
public static void main(String... args) throws IOException {
System.out.println("Main thread Started");
init();
write(input, output);
writeInThread(sec1Input, sec1Output);
writeInThread(sec2Input, sec2Output);
writeInThread(sec3Input, sec3Output);
System.out.println("Main thread Finished");
}
public static void init() throws MalformedURLException,
FileNotFoundException, SmbException, UnknownHostException {
localFile = new File("c:\\temp\\myFile.txt");
if (localFile.length() > 20971520l) {
bufferSize = 131072;
}
String server = "myServer";
String username = "myUser";
String password = "myPass";
String path = "myPath";
auth = new NtlmPasswordAuthentication(server, username, password);
input = new BufferedInputStream(new FileInputStream(localFile));
primarySmbFile = new SmbFile("smb://" + server + "/" + path
+ "/primary.txt", auth, SmbFile.FILE_SHARE_READ
| SmbFile.FILE_SHARE_WRITE | SmbFile.FILE_SHARE_DELETE);
output = new SmbFileOutputStream(primarySmbFile, append);
if (!primarySmbFile.exists()) {
primarySmbFile.createNewFile();
}
sec1Input = new BufferedInputStream(new SmbFileInputStream(new SmbFile(
primarySmbFile, primarySmbFile.getName())));
secondary1SmbFile = new SmbFile("smb://" + server + "/" + path
+ "/secondary1.txt", auth, SmbFile.FILE_SHARE_READ
| SmbFile.FILE_SHARE_WRITE | SmbFile.FILE_SHARE_DELETE);
sec1Output = new SmbFileOutputStream(secondary1SmbFile, append);
if (!secondary1SmbFile.exists()) {
secondary1SmbFile.createNewFile();
}
sec2Input = new BufferedInputStream(new SmbFileInputStream(new SmbFile(
primarySmbFile, primarySmbFile.getName())));
secondary2SmbFile = new SmbFile("smb://" + server + "/" + path
+ "/secondary2.txt", auth, SmbFile.FILE_SHARE_READ
| SmbFile.FILE_SHARE_WRITE | SmbFile.FILE_SHARE_DELETE);
sec2Output = new SmbFileOutputStream(secondary2SmbFile, append);
if (!secondary2SmbFile.exists()) {
secondary2SmbFile.createNewFile();
}
sec3Input = new BufferedInputStream(new SmbFileInputStream(new SmbFile(
primarySmbFile, primarySmbFile.getName())));
secondary3SmbFile = new SmbFile("smb://" + server + "/" + path
+ "/secondary3.txt", auth, SmbFile.FILE_SHARE_READ
| SmbFile.FILE_SHARE_WRITE | SmbFile.FILE_SHARE_DELETE);
sec3Output = new SmbFileOutputStream(secondary3SmbFile, append);
if (!secondary3SmbFile.exists()) {
secondary3SmbFile.createNewFile();
}
}
public static void write(BufferedInputStream bufferedInputStream,
SmbFileOutputStream smbFileOutputStream) throws IOException {
byte[] buffer = new byte[bufferSize];
int len = 0;
try {
while ((len = bufferedInputStream.read(buffer)) > 0) {
synchronized (lock) {
System.out.println("'" + Thread.currentThread().getName()
+ "' writing " + bufferSize + "bytes");
smbFileOutputStream.write(buffer, 0, len);
smbFileOutputStream.flush();
}
}
} catch (IOException e) {
throw e;
} finally {
try {
bufferedInputStream.close();
} catch (Exception e) {
}
try {
smbFileOutputStream.flush();
smbFileOutputStream.close();
} catch (Exception e) {
}
}
}
public static void writeInThread(
final BufferedInputStream bufferedInputStream,
final SmbFileOutputStream smbFileOutputStream) {
threadCount++;
new Thread("Secondary thread " + threadCount) {
public void run() {
System.out.println(Thread.currentThread().getName()
+ ": started");
try {
write(bufferedInputStream, smbFileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ": finished");
}
}.start();
}
}

My chat server is responding to the correct thread/client but send button must be clicked equal to the number of clients

I have made a chat server using socket that can handle multiple clients and can reply to individual clients..the client can chat only with the server..But as the number client increases, the server has to click send button as same as the client's number.....i.e; one click to reply when there is only one client connected...click twice when there is two clients and so on..... how can i solve it???
The server is like:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.swing.SwingUtilities;
public class NewClass1{
private static ServerSocket serverSocket = null;
static Socket clientSocket = null;
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
private static LinkedHashMap<String, clientThread> hm = new LinkedHashMap<String, clientThread>();
public static HashMap<String, clientThread> getinfo(){
return hm;
}
public static void main(String args[]) {
int portNumber = 22222;
if (args.length < 1) {
System.out.println("Usage: java MultiThreadChatServerSync <portNumber>\n"
+ "Now using port number=" + portNumber);
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
System.out.println("hiiiiiiiiiii");
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class clientThread extends Thread {
static String clientName = null;
private BufferedReader br=null;
private DataInputStream is = null;
private PrintStream os = null;
private static Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
private static HashMap<String, clientThread> hm = new HashMap<>();
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
this.hm=NewClass1.getinfo();
}
public void run() {
final int maxClientsCount = this.maxClientsCount;
final clientThread[] threads = this.threads;
try {
br= new BufferedReader(new InputStreamReader(System.in));
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.flush();
String name;
while (true) {
os.println("Enter your name.");
name = is.readLine().trim();
if (name.indexOf('#') == -1) {
break;
} else {
os.println("The name should not contain '#' character.");
}
}
System.out.println("\n"+name+" has joined");
os.println("Welcome " + name
+ " to our chat room.\nTo leave enter /quit in a new line.");
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] == this) {
clientName = "#"+name;
hm.put(clientName, this);
break;
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** A new user " + clientName
+ " entered the chat room !!! ***");
}
}
}
new Thread(new New()).start();
while(true){
String line=br.readLine();
if (line.startsWith("#")) {
String[] words = line.split("\\s", 2);
if (words.length > 1 && words[1] != null) {
words[1] = words[1].trim();
if (!words[1].isEmpty()) {
for(Map.Entry<String,clientThread> e:hm.entrySet()){
if(words[0].equals(e.getKey())){
clientThread get=e.getValue();
get.os.println("Server:\t" + words[1]);
os.flush();
System.out.println("\nServer to "+e.getKey()+":\t"+words[1]);
break;
}
else{
continue;
}
}
}}}
else { System.out.println("Please type #recipent's name.");
}}
} catch (IOException e) {
}
}
}
class New extends Thread{
public void run(){
DataInputStream is = null;
try {
is = new DataInputStream(NewClass1.clientSocket.getInputStream());
String lin=null;
while((lin=is.readLine())!=null)
{
//lin=is.readLine();
System.out.println(clientThread.clientName+": "+lin);
}
} catch (IOException ex) {
Logger.getLogger(New.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
is.close();
} catch (IOException ex) {
Logger.getLogger(New.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
The client is like:
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class NewClass implements Runnable {
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args) {
// The default port.
int portNumber = 22222;
// The default host.
String host = "localhost";
if (args.length < 2) {
System.out
.println("Usage: java MultiThreadChatClient <host> <portNumber>\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} else {
host = args[0];
portNumber = Integer.valueOf(args[1]).intValue();
}
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to write some data to the
* socket we have opened a connection to on the port portNumber.
*/
if (clientSocket != null && os != null && is != null) {
try {
/* Create a thread to read from the server. */
new Thread(new NewClass()).start();
while (!closed) {
String msg=inputLine.readLine();
os.println(msg.trim());
os.flush();
System.out.println("\nClient: \t"+msg);
}
/*
* Close the output stream, close the input stream, close the socket.
*/
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
/*
* Create a thread to read from the server. (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the
* server. Once we received that then we want to break.
*/
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println("\n"+responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}

Why client application doesn't get the list of the file from server directory?

In my client server application I am trying to print out the list of the file from the server's current directory. In this moment, my program is able to retrieve the name of the files and display, but the problem is, the result (with the list of the file) gets displayed in the server window what I don't expect.
I want that as soon as I send the corresponding command (from client side) it should give back the listed files in the same window (in client side).
The code I am working on is:
Server class:
package server;
import java.io.*;
import java.net.*;
public class AreaServer {
private static final int PORT = 8000;
private ServerSocket serverSocket;
public static void main(String[] args) {
int port = PORT;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
}
new AreaServer(port);
}
public AreaServer(int port) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Error in creation of the server socket");
System.exit(0);
}
while (true) {
try {
Socket socket = serverSocket.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while (true) {
String commandPWD = inputFromClient.readUTF();
String workingDir = System.getProperty("user.dir");
outputToClient.writeUTF(workingDir);
String commandGetList = inputFromClient.readUTF();
file)
File fileList = new File(".");
getFiles(fileList);//method calling
outputToClient.writeUTF(fileList.toString());
}
} catch (IOException e) {
System.err.println(e);
}
}
}
private static void getFiles(File fileList) {
File[] listOfFile = fileList.listFiles();
for (File f : listOfFile) {
if (f.isDirectory()) {
System.out.println(f.getName());
}
if (f.isFile()) {
System.out.println(f.getName());
}
}
}
}
Client class:
package clint;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class AreaClient {
private static final int PORT = 8000;
private static final String SERVER = "194.47.46.146";
public static void main(String[] args) {
String server = "localhost";
int port = PORT;
if (args.length >= 1) {
server = args[0];
}
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
new AreaClient(server, port);
}
public AreaClient(String server, int port) {
DataInputStream inputFromServer;
DataOutputStream outputToServer;
try {
Socket socket = new Socket(server, port);
inputFromServer = new DataInputStream(socket.getInputStream());
outputToServer = new DataOutputStream(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
System.out.println("Enter pwd command: ");
while (sc.hasNext()) {
String commandPWD = sc.nextLine();
outputToServer.writeUTF(commandPWD);
outputToServer.flush();
String workingDir = inputFromServer.readUTF();
System.out.println("Working directory is: " + workingDir);
System.out.println("Enter getList command: ");
String commandGetList = sc.nextLine();
outputToServer.writeUTF(commandGetList);
outputToServer.flush();
String listedFileFromSErver = inputFromServer.readUTF();
System.out.println("You have the following files in the server directory: " + listedFileFromSErver);
}
inputFromServer.close();
outputToServer.close();
socket.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
It's printing out the list of files because your getFiles method says to
if (f.isDirectory()) {
System.out.println(f.getName());
}
if (f.isFile()) {
System.out.println(f.getName());
}

How to access a file on a Client from a Server without transferring the file from the Client to the Server in Java

I am programming my first Java Socket application that uses a Client/Server paradigm.
I have the following classes:
SocketServer
SocketClient
The objective of the application is to have a user input a file path to a .csv file on the Client Console/File System:
1. Create a Server Program that uses a Socket.
a. The Server receives a CSV path/filename located on the Client from the Client.
b. The Server accesses the Client CSV file and converts it to an XML file.
c. The Server streams the XML file contents, not the XML path/file
name, back to the Client.
Create a Client Program that uses a Socket. Use the same port as the
Server.
a. Prompt the user for the path/filename of a CSV file.
b. Send the path/filename to the Server for processing.
c. Receive the XML file stream from the Server Socket.
d. Save the XML file stream to a file stored on the Client.
e. Store the generated XML file anywhere on the Client.
I have already written the code for connecting the Sockets on both the Server and Client as well as for converting the .csv to .xml, however, I am struggling with:
Step 1b.The Server accesses the Client CSV file and converts it to an
XML file.
Can I access the .csv file located on the Client directly from the Server
OR
Do I have to transfer the file path back from the Server to the Client, then transfer the file to the Server for conversion, then transfer the new XML document back?
Based on the instructions, it sounds like there should be a way to access the file from the Server.
Here is the code that I have already written.
ClientController.java
public class ClientController extends ConsoleController {
// DEBUG
private static final boolean DEBUG = true;
private static final boolean DEBUG_STORE = false;
private static final boolean DEBUG_PROMPT = false;
private static final boolean DEBUG_VALUES = true;
// CONSTANTS
public static final String PROMPT_MESSAGE = "Enter the filepath to a '.csv' file to convert to a '.xml' file: ";
// MEMBERS
private String userFilepath;
private SocketClient mClient;
// CONSTRUCTORS
public ClientController() {
super();
mClient = null;
}
// LIFE-CYCLE METHODS
#Override
public void onCreate() {
// Setup the Connection to the Server
mClient = setupServerConnection();
// Get the path to the CSV file for conversion
requestPathToCSVFile();
// Attempt to Transfer the file
try {
sendPathToServer(userFilepath);
} catch (Exception e) {
System.out.println("Failed to transfer the file!");
System.out.println("Exception: ");
e.printStackTrace();
}
// Attempt to send some message 50 times
mClient.sendSomeMessages(3);
}
// CONVENIENCE METHODS
private SocketClient setupServerConnection() {
String hostname = "localhost";
int port = 54321;
byte[] data = "Hello Server".getBytes();
return new SocketClient(hostname, port, data);
}
private void requestPathToCSVFile() {
// Debug vars
boolean isEmpty = true;
boolean isDefaultMessage = true;
boolean isCSV = false;
while (true){
if (!isEmpty && !isDefaultMessage && isCSV) break;
// Prompt user
userFilepath = promptUser(PROMPT_MESSAGE);
System.out.println(userFilepath);
// Debugging
isEmpty = userFilepath.isEmpty();
isDefaultMessage = userFilepath.equals(DEFAULT_MESSAGE);
isCSV = isCSVPath(userFilepath);
// Output Debugging
if (DEBUG && DEBUG_VALUES) {
if (userFilepath != null) {
System.out.println("DEBUG userFilepath: " + userFilepath);
} else {
System.out.println("DEBUG userFilepath: isNull");
}
System.out.println("isEmpty: " + (isEmpty? "true":"false"));
System.out.println("DEBUG userFilepath:" + (isDefaultMessage? "true":"false"));
System.out.println("isCSVPath: " + (isCSVPath(userFilepath)? "true":"false"));
}
}
}
private void sendPathToServer(String path) {
// Send the filepath to the Server
mClient.sendMessage(path);
}
private boolean isCSVPath(String path) {
return Regex.hasExtension(path, "csv");
}
}
SocketServer.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// An example of a very simple socket server.
public class SocketServer
{
// CONSTANTS
private static final boolean DEBUG = true;
private static final boolean DEBUG_NODES = true;
// FLAGS
private static final int FLAG_MESSAGE = 0;
private static final int FLAG_CONVERT_CSV_TO_XML = 1;
// CONSTANTS
private static final String TEMPORARY_FOLDER_PATH = "/tmp";
private static final String TEMP_CSV_FILENAME = "csvToConvertToXml.csv";
private static final String TEMP_XML_FILENAME = "xmlOfCsv.xml";
// MEMBERS
private int serverPort;
private ServerSocket mServerSocket = null;
private Socket mSocket;
private InputStream mSocketInput;
private OutputStream mSocketOutput;
private int mSocketFlag;
private String mPathToCsv;
public SocketServer(int serverPort)
{
this.serverPort = serverPort;
try
{
mServerSocket = new ServerSocket(serverPort);
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
}
public void waitForConnections()
{
mSocket = null;
mSocketInput = null;
mSocketOutput = null;
while (true)
{
// Open a Socket on the Server and Wait for a Connection
openSocket();
// TODO CODE THE FLAGGING
mSocketFlag = 1;
switch (mSocketFlag) {
case FLAG_MESSAGE:
handleConnection();
break;
case FLAG_CONVERT_CSV_TO_XML:
handleFileConversionConnection();
break;
}
// Now close the socket.
closeSocket();
}
}
// All this method does is wait for some bytes from the
// connection, read them, then write them back again, until the
// socket is closed from the other side.
public void handleFileConversionConnection()
{
while(true)
{
byte[] buffer = new byte[1024];
int bytes_read = 0;
try
{
// This call to read() will wait forever, until the
// program on the other side either sends some data,
// or closes the socket.
bytes_read = mSocketInput.read(buffer, 0, buffer.length);
// If the socket is closed, sockInput.read() will return -1.
if(bytes_read < 0)
{
System.err.println("Tried to read from socket, read() returned < 0, Closing socket.");
return;
}
// Set the mPathToCsv
mPathToCsv = new String(buffer, 0, bytes_read);
// Log the RECIEVED DATA
System.out.println("Server Received "+ bytes_read +" bytes, data=" + mPathToCsv);
System.out.println("mPathToCsv: " + mPathToCsv);
// Get the a the path supplied by the Client and save it in the /temp folder on the server
String pathToTempCsv = getFileFromClient(mPathToCsv,TEMPORARY_FOLDER_PATH, TEMP_CSV_FILENAME);
// Convert the Csv to XML
String pathToXmlForClient = convertCsvToXml(pathToTempCsv, TEMPORARY_FOLDER_PATH, TEMP_XML_FILENAME);
// Transfer the new XML Document to the Client
//transfer(pathToXmlForClient);
//
mSocketOutput.write(buffer, 0, bytes_read);
// This call to flush() is optional - we're saying go
// ahead and send the data now instead of buffering it.
mSocketOutput.flush();
}
catch (Exception e)
{
System.err.println("Exception reading from/writing to socket, e="+e);
e.printStackTrace(System.err);
return;
}
}
}
// All this method does is wait for some bytes from the
// connection, read them, then write them back again, until the
// socket is closed from the other side.
public void handleConnection()
{
while(true)
{
byte[] buffer = new byte[1024];
int bytes_read = 0;
try
{
// This call to read() will wait forever, until the
// program on the other side either sends some data,
// or closes the socket.
bytes_read = mSocketInput.read(buffer, 0, buffer.length);
// If the socket is closed, sockInput.read() will return -1.
if(bytes_read < 0)
{
System.err.println("Tried to read from socket, read() returned < 0, Closing socket.");
return;
}
System.out.println("Server Received "+ bytes_read +" bytes, data=" + (new String(buffer, 0, bytes_read)));
mSocketOutput.write(buffer, 0, bytes_read);
// This call to flush() is optional - we're saying go
// ahead and send the data now instead of buffering it.
mSocketOutput.flush();
}
catch (Exception e)
{
System.err.println("Exception reading from/writing to socket, e="+e);
e.printStackTrace(System.err);
return;
}
}
}
public void openSocket() {
try
{
// This method call, accept(), blocks and waits
// (forever if necessary) until some other program
// opens a socket connection to our server. When some
// other program opens a connection to our server,
// accept() creates a new socket to represent that
// connection and returns.
mSocket = mServerSocket.accept();
System.err.println("Have accepted new socket.");
// From this point on, no new socket connections can
// be made to our server until accept() is called again.
mSocketInput = mSocket.getInputStream();
mSocketOutput = mSocket.getOutputStream();
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
}
public void closeSocket() {
try
{
System.err.println("Closing socket.");
mSocket.close();
}
catch (Exception e)
{
System.err.println("Exception while closing socket.");
e.printStackTrace(System.err);
}
System.err.println("Finished with socket, waiting for next connection.");
}
// CONVENIENCE METHODS
public void transfer(String sfile) throws IOException {
if (DEBUG && DEBUG_NODES) System.out.println("Enter transfer(String sfile)");
// Create a new File object
File myFile = new File(sfile);
while (true) {
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
// Get the OutputStream for the Socket
mSocketOutput.write(mybytearray, 0, mybytearray.length);
mSocketOutput.flush();
// Close the socket
bis.close();
}
}
public String getFileFromClient(String pathToFile, String destinationDirectory, String newFilename) {
if (DEBUG && DEBUG_NODES) System.out.println("Enter getFileFromClient(String pathToFile, String destinationDirectory, String newFilename)");
String pathToNewFile = destinationDirectory + "/" + newFilename;
// TODO GET THE FILE FROM THE CLIENT
if (DEBUG && DEBUG_NODES) System.out.println("Exit getFileFromClient(String pathToFile, String destinationDirectory, String newFilename)");
return pathToNewFile;
}
public String convertCsvToXml(String pathToCsv, String pathToDestinationDirectory, String newFilename) {
if (DEBUG && DEBUG_NODES) System.out.println("Enter convertCsvToXml(String pathToCsv, String pathToDestinationDirectory, String newFilename)");
String pathToNewFile = pathToDestinationDirectory + "/" + newFilename;
// TODO CREATE THE NEW FILE AND CONVERT THE CSV TO XML
XMLWriter xmlFile = new XMLWriter(pathToCsv, pathToNewFile);
xmlFile.csvToXml();
if (DEBUG && DEBUG_NODES) System.out.println("Exit convertCsvToXml(String pathToCsv, String pathToDestinationDirectory, String newFilename)");
return pathToNewFile;
}
public static void main(String argv[])
{
int port = 54321;
SocketServer server = new SocketServer(port);
server.waitForConnections();
}
}
SocketClient.java
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketClient
{
// CONSTANTS
public static final int TRANSFER_SIZE_1KB = 1024;
// MEMBERS
private String mServerHostname = null;
private int mServerPort = 0;
private byte[] data = null;
private Socket mSocket = null;
private InputStream mSocketInput = null;
private OutputStream mSocketOutput = null;
public SocketClient(String ServerHostname, int ServerPort)
{
this(ServerHostname, ServerPort, null);
}
public SocketClient(String mServerHostname, int mServerPort, byte[] data)
{
this.mServerHostname = mServerHostname;
this.mServerPort = mServerPort;
this.data = data;
}
public void transfer( String outfile ) throws Exception {
// Open the Socket
openSocket();
// Create a new byte array size of 1KB
byte[] bytearray = new byte[TRANSFER_SIZE_1KB];
// Create a bufferedOutputStream from the outfile path
FileOutputStream fos = new FileOutputStream(outfile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
// TESTING
fos.toString();
// Initialize values to 0
int bytesRead = 0;
int count = 0;
System.out.println("GOT HERE");
// Transfer the 'outfile' 1KB (1024 bytes) increments, each pass is 1KB chunk of files
while ((bytesRead = mSocketInput.read(bytearray, 0, bytearray.length)) != -1)
{
System.out.println("GOT HERE");
// Send the data to the Server
bos.write(bytearray, 0, bytesRead);
// If less than 1KB, finish the transfer using flush()
bos.flush();
System.out.println(++count);
}
// Log to console
System.out.println("Finished transferring " + outfile);
// Close the bufferedOutputStream
bos.close();
// Close the socket
closeSocket();
}
public void sendSomeMessages(int iterations)
{
// Open the Socket
openSocket();
byte[] buf = new byte[data.length];
int bytes_read = 0;
for(int x=1; x<=iterations; x++)
{
try
{
mSocketOutput.write(data, 0, data.length);
bytes_read = mSocketInput.read(buf, 0, buf.length);
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
if( bytes_read != data.length )
{
System.out.println("run: Sent "+ data.length +" bytes, server should have sent them back, read "+bytes_read+" bytes, not the same number of bytes.");
}
else
{
System.out.println("Client Sent "+bytes_read+" bytes to server and received them back again, msg = "+(new String(data)));
}
// Sleep for a bit so the action doesn't happen to fast -
// this is purely for reasons of demonstration, and not required technically.
try { Thread.sleep(50);}
catch (Exception e) {};
}
System.err.println("Done reading/writing to/from socket, closing socket.");
// Close the Socket
closeSocket();
}
public void sendMessage(String str) {
// Open the Socket
openSocket();
// Convert the String to a Byte Array
byte[] data = str.getBytes();
// Create a buffer object the size of the data byte array
byte[] buf = new byte[data.length];
int bytes_read = 0;
// Attempt to send the data over the network
try
{
mSocketOutput.write(data, 0, data.length);
bytes_read = mSocketInput.read(buf, 0, buf.length);
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
if( bytes_read != data.length )
{
System.out.println("run: Sent "+ data.length +" bytes, server should have sent them back, read "+bytes_read+" bytes, not the same number of bytes.");
}
else
{
System.out.println("Client Sent "+bytes_read+" bytes to server and received them back again, msg = "+(new String(data)));
}
// Sleep for a bit so the action doesn't happen to fast -
// this is purely for reasons of demonstration, and not required technically.
try { Thread.sleep(50);}
catch (Exception e) {};
System.err.println("Done reading/writing to/from socket, closing socket.");
// Close the Socket
closeSocket();
}
public void openSocket() {
// Open the Socket
System.err.println("Opening connection to "+mServerHostname+" port "+mServerPort);
try
{
mSocket = new Socket(mServerHostname, mServerPort);
mSocketInput = mSocket.getInputStream();
mSocketOutput = mSocket.getOutputStream();
}
catch (IOException e)
{
e.printStackTrace(System.err);
return;
}
System.err.println("About to start reading/writing to/from socket.");
}
public void closeSocket() {
// Close the Socket
try
{
mSocket.close();
}
catch (IOException e)
{
System.err.println("Exception closing socket.");
e.printStackTrace(System.err);
}
System.err.println("Exiting.");
}
// GETTERS & SETTERS
public String getServerHostname() {
return mServerHostname;
}
public void setServerHostname(String serverHostname) {
this.mServerHostname = mServerHostname;
}
public int getServerPort() {
return mServerPort;
}
public void setServerPort(int serverPort) {
this.mServerPort = mServerPort;
}
public Socket getSocket() {
return mSocket;
}
public void setSocket(Socket socket) {
this.mSocket = mSocket;
}
public InputStream getSocketInput() {
return mSocketInput;
}
public void setSocketInput(InputStream socketInput) {
this.mSocketInput = mSocketInput;
}
public OutputStream getSocketOutput() {
return mSocketOutput;
}
public void setSocketOutput(OutputStream socketOutput) {
this.mSocketOutput = mSocketOutput;
}
}
SUPPORTING CLASSES
ConsoleController.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
#SuppressWarnings("unused")
public abstract class ConsoleController {
// DEBUG
private static final boolean DEBUG = false;
private static final boolean DEBUG_STORE = false;
private static final boolean DEBUG_PROMPT = false;
private static final boolean DEBUG_VALUES = false;
// CONSTANTS
protected static final String DEFAULT_MESSAGE = "No input recieved";
// MEMBERS
private String mRecentInput;
// CONSTRUCTORS
public ConsoleController() {
mRecentInput = DEFAULT_MESSAGE;
}
// LIFE-CYCLE METHODS
abstract public void onCreate();
public String promptUser(String userPrompt) {
System.out.println(userPrompt);
try{
// Create BufferedReader to read from the Console
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
// Read the line from the console
mRecentInput = bufferRead.readLine();
if (mRecentInput.equalsIgnoreCase("Exit")) exit();
}
catch(IOException e)
{
e.printStackTrace();
}
return mRecentInput;
}
public String getInput() {
return mRecentInput;
}
public void exit() {
//System.out.println("Quiting");
System.exit(0);
}
}
Regex.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
#SuppressWarnings("unused")
public class Regex {
public static final boolean DEBUG = false;
public static final boolean DEBUG_HAS_EXT = true;
public static boolean hasExtension(String path, String extension) {
// Match Numberic and Hexadecimal Values
Pattern extTest = Pattern.compile("\\.(" + extension.trim() + ")$");
Matcher values = extTest.matcher(path);
if (DEBUG && DEBUG_HAS_EXT) {
System.out.println("Regex - Extension Matches");
System.out.println("Search String: " + path);
System.out.println("Pattern: " + extTest.pattern());
System.out.print("Match: ");
}
// Returns true if there is anotherMatch remaining, returns false if no matches remain
boolean anotherMatch = values.find();
if (anotherMatch == true) {
while(anotherMatch) {
// If we get here, there is a match
// Log
if (DEBUG && DEBUG_HAS_EXT) System.out.println(values.group());
// Check to see if there is anotherMatch
anotherMatch = values.find();
}
return true;
} else {
if (DEBUG && DEBUG_HAS_EXT) System.out.println("There was no match");
return false;
}
}
}
XMLWriter.java
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class XMLWriter
{
// Members
private Document mDocumentForOutput;
private String mInFilePath;
private String mOutFilePath;
// CONSTRUCTORS
public XMLWriter(String filePathForConversion, String filePathForOutput) {
mInFilePath = filePathForConversion;
mOutFilePath = filePathForOutput;
try {
mDocumentForOutput = createDocument();
} catch (Exception e) {
System.out.println("Exception: ");
e.printStackTrace();
}
}
public Document createDocument() throws IOException, ParserConfigurationException
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
return doc;
}
public void processDocument(String delimeter) throws Exception
{
// Get a File object from the InPath
File inFile = new File(mInFilePath);
// Create a BufferedReader from the file
BufferedReader reader = new BufferedReader(new FileReader(inFile));
// Read a line from the file
String sline = reader.readLine();
//
String[] sheaders = sline.split(delimeter);
sline = reader.readLine();
String[] snodes = sline.split(delimeter);
Element aroot;
Element achild;
aroot = mDocumentForOutput.createElement(sheaders[0].trim());
mDocumentForOutput.appendChild(aroot);
while ((sline=reader.readLine()) != null)
{
achild = mDocumentForOutput.createElement(sheaders[1].trim());
String[] sdata = sline.split(delimeter);
for (int x=0; x<snodes.length; ++x)
{
Element c = mDocumentForOutput.createElement(snodes[x].trim());
c.appendChild(mDocumentForOutput.createTextNode(sdata[x].trim()));
achild.appendChild(c);
}
aroot.appendChild(achild);
}
}
public void createXML() throws Exception
{
//TransformerFactory instance is used to create Transformer objects.
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(mDocumentForOutput);
transformer.transform(source, result);
String xmlString = sw.toString();
File file = new File(mOutFilePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(xmlString);
bw.flush();
bw.close();
}
public void createXmlDocument(String delimeter) throws Exception
{
processDocument(delimeter);
createXML();
}
public void csvToXml() {
try {
createXmlDocument(",");
} catch (Exception e) {
System.out.print("Exception: ");
e.printStackTrace();
}
}
public static void testWriter(String csvFile)
{
try
{
try {
XMLWriter xmlWriter = new XMLWriter(csvFile, "Output.xml");
xmlWriter.csvToXml();
} catch (Exception e) {
System.out.println("'" + csvFile + "' does not exist in the given directory! Please check that you have properly entered your filepath");
}
System.out.println("<b>Xml File Created Successfully</b>");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Java Socket - Sending files over sockets

I've been working on a Client/Server project and I'm stuck. I'm trying to write a back-up server so I can back-up my files to a remote computer. The problem is when I try to back-up my /home/user file, it gives me the following error on the server side:
java.io.UTFDataFormatException: malformed input around byte ...
I first send the size of the file, then I read the file into a byte array and then is send this byte array at once to the server, who receives it in a byte array it constructed using the file size. Is it a better solution to divide files into chunks or will the error remain?
This usually happens on a .zip file, but it doesn't always happen so that is why I'm confused. Can anyone help me out?
Code:
Server:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket server;
private Socket acceptingSocket;
public Server(int port){
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Try again");
}
}
public void run(){
BufferedInputStream buffer = null;
DataInputStream reader = null;
int size = 0;
try {
acceptingSocket = server.accept();
buffer = new BufferedInputStream(acceptingSocket.getInputStream());
reader = new DataInputStream(buffer);
size = reader.readInt();
} catch (IOException e1) {
}
System.out.println("Size: " + size);
for(int j = 0; j < size; j++){
try {
String path = reader.readUTF();
System.out.println("Path: " + path);
long length = reader.readLong();
System.out.println("Length: "+length);
boolean dir = reader.readBoolean();
System.out.println("Dir? " + dir);
path = "/backup" + path;
File file = new File(path);
if(!dir){
int t = file.getAbsolutePath().lastIndexOf("/");
String dirs = file.getAbsolutePath().substring(0, t);
File direcs = new File(dirs);
System.out.println(direcs.mkdirs());
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[(int) length];
int bytes = reader.read(b, 0, (int)length);
if(bytes != -1)
bos.write(b,0,(int)length);
BufferedOutputStream out = new BufferedOutputStream(acceptingSocket.getOutputStream());
DataOutputStream writer = new DataOutputStream(out);
writer.writeUTF("File " + file.getAbsolutePath() + " is created!");
writer.flush();
bos.close();
} else file.mkdirs();
} catch (IOException e) {
System.out.println(e);
}
}
}
public static void main(String[] args){
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
while(true)
server.run();
}
}
Client:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Client {
private DataInputStream serverToClient;
private Socket client;
private DataOutputStream clientToServer;
private String name;
public Client(String name, int port){
try {
client = new Socket(name, port);
//receive response server
serverToClient = new DataInputStream(client.getInputStream());
//send message to server
clientToServer = new DataOutputStream(client.getOutputStream());
this.name = name;
}
catch (IOException e) {
}
}
public void backUp(String filePath){
File file = new File(filePath);
CopyOnWriteArrayList<File> files = new CopyOnWriteArrayList<File>();
if(file.exists()){
try{
if(file.isDirectory()){
ArrayList<File> f = setToList(file.listFiles());
files.addAll(f);
for(File sendF : files){
if(sendF.isDirectory()){
files.addAll(setToList(sendF.listFiles()));
if(!setToList(sendF.listFiles()).isEmpty()) files.remove(sendF);
}
}
} else{
files.add(file);
}
clientToServer.writeInt(files.size());
for(File fi : files){
boolean dir = false;
if(fi.isDirectory()) dir = true;
clientToServer.writeUTF(fi.getAbsolutePath());
System.out.println(fi.getAbsolutePath());
long length = fi.length();
clientToServer.writeLong(length);
clientToServer.writeBoolean(dir);
System.out.println(length);
if(!dir){
FileInputStream fis = new FileInputStream(fi);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[(int)length];
bis.read(buffer, 0, (int)length);
clientToServer.write(buffer);
System.out.println(serverToClient.readUTF());
bis.close();
fis.close();
}
}
} catch(IOException e){
}
} else System.out.println("File doesn't exist");
}
private ArrayList<File> setToList(File[] listFiles) {
ArrayList<File> newFiles = new ArrayList<File>();
for(File lf : listFiles){
newFiles.add(lf);
}
return newFiles;
}
public static void main(String[] args){
String name = args[0];
int port = Integer.parseInt(args[1]);
System.out.println("Name: " + name + " Port: " + port);
Client client = new Client(name, port);
File file = new File(args[2]);
if(file.exists())client.backUp(args[2]);
else System.out.println("File doesn't exist");
}
}

Categories

Resources