I am trying to write a code that would enable one user to send to or receive from another user. I have written a method to send file called sendFile, it shows that it has sent file but I cannot find where the sent file is saved.
Server side:
package DFT;
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.FileOutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerSide {
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
public static void main(String args[]) {
try {
serverSocket = new ServerSocket(2222);
System.out.println("Distributed File Transfer Server has successfully started");
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = serverSocket.accept();
int i;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
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.err.println(e);
}
}
}
}
class clientThread extends Thread {
// private DataInputStream is = null;
private PrintStream os = null;
private BufferedReader is;
// private PrintWriter os;
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
private String name, pass;
private int id;
private static final int totalUser = 5;
private static final String username[] = new String[totalUser];
private static final String password[] = new String[totalUser];
private static boolean online[] = new boolean[totalUser];
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
username[0] = "user1";
username[1] = "user2";
username[2] = "user3";
username[3] = "user4";
username[4] = "user5";
password[0] = "123";
password[1] = "456";
password[2] = "789";
password[3] = "012";
password[4] = "345";
maxClientsCount = threads.length;
}
#Override
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
try {
/*
* Create input and output streams for this client.
*/
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
if (is.readLine().trim().equals("login")) {
name = is.readLine().trim();
pass = is.readLine().trim();
}
int i, j;
for (i = 0; i < totalUser; i++) {
if (name.equals(username[i]) && pass.equals(password[i])) {
break;
}
}
if (i < totalUser) {
if (online[i]) {
os.println("This user already logged in");
threads[i] = null;
is.close();
os.close();
clientSocket.close();
return;
} else {
for (j = 0; j < maxClientsCount; j++) {
if (threads[j] == this) {
threads[j].id = i;
online[i] = true;
}
if (threads[j] != null) {
threads[j].os.println("<Server Message>: A new user " + name + " has logged in");
}
}
}
} else {
os.println("Invalid Username & Password. Terminating");
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
is.close();
os.close();
clientSocket.close();
return;
}
}
}
while (true) {
String line = is.readLine();
System.out.println("#### " + line);
if (line.startsWith("logout")) {
os.println("Successfully logged out");
online[id] = false;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] != null) {
if (threads[i] == this)
threads[i] = null;
else
threads[i].os.println("<Server message>: " + name + " has logged out");
}
}
is.close();
os.close();
clientSocket.close();
return;
}
if (line.startsWith("sendfile ")) {
String subline = line.substring(15);
String temp = line.substring(9, 14);
for (i = 0; i < totalUser; i++) {
if (username[i].equals(temp)) {
break;
}
}
if (i == totalUser) {
os.println("Invalid username");
continue;
}
int k = i;
if (!online[k]) {
os.println("<Failure>: " + temp + " is not online");
} else {
os.println("file sent");
for (j = 0; j < maxClientsCount; j++) {
if (threads[j] != null && threads[j].id == k) {
threads[j].os.println("<" + name + "> " + subline);
}
}
sendFile(subline);
break;
}
}
if (line.startsWith("send ")) {
String subline = line.substring(11);
String temp = line.substring(5, 10);
for (i = 0; i < totalUser; i++) {
if (username[i].equals(temp)) {
break;
}
}
if (i == totalUser) {
os.println("Invalid username");
continue;
}
int k = i;
if (!online[k]) {
os.println("<Failure>: " + temp + " is not online");
}
else {
os.println("message sent");
for (j = 0; j < maxClientsCount; j++) {
if (threads[j] != null && threads[j].id == k) {
threads[j].os.println("<" + name + ">: " + subline);
}
}
}
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = null;
try {
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
clientData = dataInputStream;
} catch (IOException e) {
System.err.println(e);
}
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File " + fileName + " received from client.");
} catch (IOException e) {
System.err.println(e);
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
File file = new File(fileName);
byte[] bytearray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytearray, 0, bytearray.length);
OutputStream os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(bytearray.length);
dos.write(bytearray, 0, bytearray.length);
dos.flush();
System.out.println("File " + fileName + " sent to client.");
} catch (IOException e) {
System.err.println("File does not exist!");
System.err.println(e);
}
}
}
Client side:
package DFT;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSide implements Runnable {
private static Socket clientSocket = null;
private static PrintStream os = null;
// private static PrintWriter os;
// private static DataInputStream is = null;
private static BufferedReader inputLine, is;
private static boolean closed = false;
private static String username, password;
public static void main(String[] args) {
try {
clientSocket = new Socket("localhost", 2222);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException unknownHostException) {
System.err.println("Don't know about host");
System.err.print(unknownHostException);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host");
System.err.println(e);
}
if (clientSocket != null && os != null && is != null) {
try {
// Creates a thread to read from the server.
new Thread(new ClientSide()).start();
System.out.println("Enter UserName:");
username = inputLine.readLine().trim();
System.out.println("Enter Password:");
password = inputLine.readLine().trim();
os.println("login");
os.println(username);
os.println(password);
while (!closed) {
os.println(inputLine.readLine().trim());
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
#Override
public void run() {
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1) {
break;
}
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = null;
try {
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
clientData = dataInputStream;
} catch (IOException e) {
System.err.println(e);
}
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File " + fileName + " received from client.");
} catch (IOException e) {
System.err.println(e);
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
File file = new File(fileName);
byte[] bytearray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytearray, 0, bytearray.length);
OutputStream os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(bytearray.length);
dos.write(bytearray, 0, bytearray.length);
dos.flush();
System.out.println("File " + fileName + " sent to client.");
} catch (IOException e) {
System.err.println("File does not exist!");
System.err.println(e);
}
}
}
It looks like your receiveFile() method is creating the file, but it is never called in your code.
Related
Screenshot of program running (top is server, bottom right is first client, bottom left is second client):
Screenshot of program running
The problem with the screenshot above is that the message that appears on the bottom left window User name: something has been added to position 0 in the namesList array should instead be User name: something has been added to position 1 in the namesList array The reason the position needs to be 1 instead of 0 is because the first name should be stored in the first position, and the second name should be stored in the second position (to make the list of names actually store all of the names)
The issue is making the namesList array and position sync.
EDIT: it seems that threads[i] has global accessibility, is it possible that I should make an arraylist of file names with objects to somehow store the names of the connected clients instead of a regular string array to store them?
What changes can I make to the following code that would make the array sync and accessible to all clients?
ChatThreads.java code:
import java.io.*;
import java.net.*;
import java.util.*;
class ClientThreads extends Thread
{
public String name1 = "";
private String clientName = null;
private DataInputStream is = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final ClientThreads[] threads;
private int maxClientsCount;
public static String[] namesList = new String[4];
public int iteration = 0;
public static String[] responses = new String[50];
public int responseCount = 0;
public ClientThreads(Socket clientSocket, ClientThreads[] threads, String name)
{
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
this.name1 = name;
}
#SuppressWarnings("deprecation")
public void run()
{
int maxClientsCount = this.maxClientsCount;
ClientThreads[] threads = this.threads;
for(int i = 0; i < namesList.length; i++)
{
namesList[i] = "";
}
for(int j = 0; j < responses.length; j++)
{
responses[j] = "";
}
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
String name;
String firstName;
while (true)
{
os.println("What is your name?");
name = is.readLine().trim();
break;
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] == this)
{
clientName = "#" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null)
{
threads[i].os.println(name + " has connected.");
os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
}
}
while (true)
{
String line = is.readLine();
if (line.startsWith("/quit"))
{
break;
}
else
{
//os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
if(line.equals("x") || line.equals("X"))
{
os.println("x");
System.exit(0);
}
if(line.equals("m") || line.equals("M"))
{
os.println("Enter your message: ");
}
if(line.equals("f") || line.equals("F"))
{
os.println("Who owns the file?");
boolean keep = true;
while (keep == true)
{
String fileOwner = is.readLine();
if(fileOwner !=null && !fileOwner.isEmpty())
{
responses[responseCount] = fileOwner + "`owns a file";
responseCount++;
os.println(fileOwner);
namesList[iteration] = fileOwner;
System.out.println("User named: " + fileOwner + " has been added to position " + iteration + " in the namesList array.");
iteration++;
keep = false;
os.println("Which file do you want?");
boolean keep2 = true;
while(keep2==true)
{
String filename = is.readLine();
if(filename !=null && !filename.isEmpty())
{
// os.println(filename);
keep2 = false;
os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
}
}
}
}
else
{
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (!line.equals("x") && !line.equals("X") && !line.equals("f") && !line.equals("F") && !line.equals("m") && !line.equals("M") && threads[i] != null && threads[i].clientName != null && !threads[i].clientName.equals("m") && !threads[i].clientName.equals("M"))
{
threads[i].os.println(name + ": " + line + "\n");
this.os.println("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n");
}
}
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] != null && threads[i] != this && threads[i].clientName != null)
{
threads[i].os.println(name + "has disconnected.");
}
}
}
synchronized (this)
{
for (int i = 0; i < maxClientsCount; i++)
{
if (threads[i] == this)
{
threads[i] = null;
}
}
}
is.close();
os.close();
clientSocket.close();
}
catch (IOException e)
{
}
}
}
ChatClient.java code:
import java.io.*;
import java.net.*;
public class ChatClient implements Runnable
{
private static Socket clientSocket = null;
private static PrintStream os = null;
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static String[] namesList = new String[4];
public int iteration = 0;
public static String[] responses = new String[50];
public int responseCount = 0;
public static void main(String[] args)
{
for(int i = 0; i < namesList.length; i++)
{
namesList[i] = "";
}
for(int j = 0; j < responses.length; j++)
{
responses[j] = "";
}
int portNumber = Integer.valueOf(args[3]);
String host = "localhost";
int filePort = Integer.valueOf(args[1]);
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 (clientSocket != null && os != null && is != null)
{
try
{
new Thread(new ChatClient()).start();
while (!closed)
{
os.println(inputLine.readLine() );
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
#SuppressWarnings("deprecation")
public void run()
{
String responseLine = "";
try
{
while ((responseLine = is.readLine()) != null)
{
if(responseLine.equals("x") || responseLine.equals("X"))
{
System.exit(0);
}
if(responseLine.equals("Who owns the file?") && !responseLine.isEmpty() && responseLine != null)
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = "234782375920192831";
}
if(responseLine.equals("Which file do you want?"))
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
if(responseLine.equals("What is your name?"))
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
if(responseLine.equals("m") || responseLine.equals("M"))
{
responseCount++;
System.out.println("Enter your message: ");
responses[responseCount] = responseLine;
}
if(responseLine.equals("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n"))
{
responseCount++;
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
if(responseLine != null && !responseLine.isEmpty() && !responseLine.equals("What is your name?") && !responseLine.equals("Enter an option: 'm' = message, 'f' = file request, 'x' = exit\n") && !responseLine.equals("Who owns the file?") && !responseLine.equals("Which file do you want?"))
{
responseCount++;
if(responses[responseCount-1].equals("234782375920192831"))
{
namesList[iteration] = responseLine;
System.out.println("User named: " + responseLine + " has been added to position " + iteration + " in the namesList array." );
iteration++;
}
else
{
System.out.println(responseLine);
responses[responseCount] = responseLine;
}
}
}
closed = true;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
}
ChatServer.java code
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static ServerSocket serverSocket = null;
public static Socket clientSocket = null;
public static final int maxClientsCount = 10;
public static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static void main(String args[])
{
if(args.length <3)
{
int portNumber = Integer.valueOf(args[1]).intValue();
System.out.println("waiting for connections on port " + portNumber + " ...\n ");
}
try
{
int portNumber1 = Integer.valueOf(args[1]).intValue();
serverSocket = new ServerSocket(portNumber1);
}
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)
{
String name = "";
(threads[i] = new ClientThreads(clientSocket, threads, name)).start();
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);
}
}
}
}
ServerThread.java code:
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerThread
{
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static final int maxClientsCount = 10;
private static final ClientThreads[] threads = new ClientThreads[maxClientsCount];
public static void main(String args[])
{
int portNumber = Integer.valueOf(args[1]).intValue();
if(args.length <3)
{
System.out.println("waiting for conennections on port" + portNumber + " ...\n ");
}
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)
{
String name = "";
(threads[i] = new ClientThreads(clientSocket, threads, name)).start();
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);
}
}
}
}
My question is: How would I make the namesList array the same across multiple clients with the position?
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
package main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
public class FileTransfer {
private Socket socket;
private static final int MAX_BUFFER = 8192;
public FileTransfer(Socket socket) {
this.socket = socket;
}
public boolean sendFile(File file) {
boolean errorOnSave = false;
long length = file.length();
if (file.exists()) {
FileInputStream in = null;
DataOutputStream out = null;
try {
in = new FileInputStream(file);
out = new DataOutputStream(this.socket.getOutputStream());
out.writeLong(length);
out.flush();
byte buffer[] = new byte[MAX_BUFFER];
int read = 0;
int i=0;
while ((read = in.read(buffer)) != -1) {
System.out.println(i);
i++;
out.write(buffer, 0, read);
out.flush();
buffer = new byte[MAX_BUFFER];
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return false;
} catch (IOException e) {
System.out.println("An error has occurred when try send file " + file.getName() + " \nSocket: "
+ socket.getInetAddress() + ":" + socket.getPort() + "\n\t" + e);
errorOnSave = true;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("An error has occurred when closing the InputStream of the file "
+ file.getName() + "\n\t" + e.getMessage());
}
}
}
return !errorOnSave;
} else {
return false;
}
}
public boolean saveFile(File fileSave) {
RandomAccessFile file = null;
DataInputStream in = null;
boolean errorOnSave = false;
try {
file = new RandomAccessFile(fileSave, "rw");
file.getChannel().lock();
in = new DataInputStream(this.socket.getInputStream());
long fileSize = in.readLong();
byte buffer[] = new byte[MAX_BUFFER];
int read = 0;
while ((fileSize > 0) && ((read = in.read(buffer, 0, (int) Math.min(buffer.length, fileSize))) != -1)) {
file.write(buffer, 0, read);
fileSize -= read;
buffer = new byte[MAX_BUFFER];
}
} catch (FileNotFoundException e1) {
System.out.println(e1.getMessage());
return false;
} catch (IOException e) {
System.out.println("An error has occurred when saving the file\n\t" + e.getMessage());
errorOnSave = true;
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println(
"An error occurred when closing the file " + fileSave.getName() + "\n\t" + e.getMessage());
errorOnSave = true;
}
}
if (errorOnSave) {
if (fileSave.exists()) {
fileSave.delete();
}
}
}
return !errorOnSave;
}
}
I have a problem with my java project(its going to send files from server to client...) its always telling me after a few seconds
"Connection reset by peer: socket write error" if someone has the answear please tell whats wrong with my code.....
I had this issue recently: Try this
setBufferSize(1024*1024);
setKeepAlive(false);
Also check if you are on the same WLAN connection (both your device and the server itself)
I hope this helps you get something going!
I have written a multi-client TCP server that has the dual purpose of sending Json (text based) command strings and also sending an SQLite database file to multiple clients. Everything is working nicely except... the database file uses the special character hex81 (decimal 129) for some internal purpose. When I read the database file into a byte array, Java converts this character to decimal -127 because of Java's signed representation of bytes. However the socket is actually transmitting this character as hex3F. So when I receive the save the data in the client and save it to a file, the database is corrupt due to the presence of h3F chars instead of h81.
Why is this happening and how do I correct it?
Here is the complete code that I am using for the server (a new instance of this class is started by a separate TCPServer class whenever a client connects):
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static ByteArrayOutputStream txBuffer2 = new ByteArrayOutputStream();
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private DataOutputStream out2 = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new DataOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (txBuffer2.size() != 0) {
byte[] result = txBuffer2.toByteArray();
System.out.println(result[745] + "," + result[746] + "," + result[747] + "," + result[748] + "," + result[749] + "," + result[750]);
out2.write(result);
out2.flush();
txBuffer2.reset();
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
synchronized (txBuffer2) {
file = new File(filename);
byte[] content = new byte[(int)file.length()];
FileInputStream fin;
try {
fin = new FileInputStream(file);
fin.read(content);
System.out.println(content[745] + "," + content[746] + "," +content[747] + "," +content[748] + "," + content[749] + "," + content[750]);
txBuffer2.write(content);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
}
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
So as EJP suggested, the problem is due to using readers and writers.
The following code now works as expected (thanks for the tip EJP). I will get around to addressing the issue raised by VGR about wrapping client.getOutputStream() in both a PrintWriter and a BufferedOutputStream, but for now the code works nicely (this is a work in progress).
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static BufferedOutputStream out2 = null;
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private static BufferedInputStream fileData = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new BufferedOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (fileData != null) {
byte[] buffer = new byte[(int) file.length()];
for (int read = fileData.read(buffer); read >=0; read = fileData.read(buffer)) out2.write(buffer, 0, read);
out2.flush();
fileData = null;
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
file = new File(filename);
try {
fileData = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
i am really stuck with a little project i'm doing. I am trying to send music files (only .wav) over a socket from a server to a client. Everything works perfectly fine (i think...) except that the file that is received by the client isn't complete. I can't play the file and I can see that it is a bit smaller than the one the server has. What am I doing not right?
Here is the server code:
private Socket client;
private String filename;
private TBMCAudioServer ac;
private FileInputStream fis;
private BufferedOutputStream out;
int bufferSize = 0;
FileSender(Socket client, String filename, TBMCAudioServer ac){
this.client = client;
this.filename = filename;
this.ac = ac;
}
#Override
public void run(){
ac.ex.sendMessage(client, "[#preload#]" + filename);
File dir = new File(ac.getDataFolder() + File.separator + "music");
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dir, filename + ".wav");
long length = file.length();
if(length > Integer.MAX_VALUE){
logger.info("File is too large.");
}
byte[] bytes = new byte[(int) length];
try{
fis = new FileInputStream(file);
out = new BufferedOutputStream(client.getOutputStream());
} catch (IOException e){
logger.info(e.getMessage());
}
int count;
try {
while((count = fis.read(bytes,0,bytes.length)) != -1){
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
} catch (IOException e) {
logger.info(e.getMessage());
}
}
and here you can see my client code:
private Socket server;
private String filename;
private AudioClient ac;
InputStream is = null;
FileOutputStream fos = null;
int bufferSize = 0;
FileReceiver(Socket server, String filename, AudioClient ac){
this.server = server;
this.filename = filename;
this.ac = ac;
}
#Override
public void run() {
try{
is = server.getInputStream();
bufferSize = server.getReceiveBufferSize();
ac.logConsole("Buffer size: " + bufferSize);
} catch (IOException ex){
ac.logConsole(ex.getMessage());
}
try{
fos = new FileOutputStream(AudioClient.util.getLineValue(3) + filename + ".wav");
} catch (FileNotFoundException e){
ac.logConsole(e.getMessage());
}
byte[] bytes = new byte[bufferSize];
int count;
try {
while((count = is.read(bytes, 0, bytes.length)) != -1){
fos.write(bytes, 0, count);
}
ac.logConsole("yay");
is.close();
fos.flush();
fos.close();
} catch (IOException e) {
ac.logConsole(e.getMessage());
}
}
Okay I managed to send the file fully so I can see it has the same size as where it came from with my new code. The only problem is that i'm sending a music file and I can't play the file that is sent. Maybe someone knows what the problem is?
Server code:
package me.Ciaran.simplefileserver;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String FILE_TO_SEND = "D:/server/plugins/TBMCAudioServer/music/DLTALL.wav"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
final File myFile= new File(FILE_TO_SEND); //sdcard/DCIM.JPG
byte[] mybytearray = new byte[8192];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
try {
os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
int read;
while((read = dis.read(mybytearray)) != -1){
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
and here is the client code:
package me.Ciaran.simplefileclient;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String SERVER = "127.0.0.1"; // localhost
public final static String
FILE_TO_RECEIVED = "C:/Users/Ciaran/Documents/TESTEN/music/DLTALL.wav"; // you may change this, I give a
// different name because i don't want to
// overwrite the one used by server...
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
InputStream in;
int bufferSize=0;
try {
bufferSize=sock.getReceiveBufferSize();
in=sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.println(fileName);
OutputStream output = new FileOutputStream(FILE_TO_RECEIVED);
byte[] buffer = new byte[bufferSize];
int read;
while((read = clientData.read(buffer)) != -1){
output.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
i have written a java code to transfer files from one server to another using the concept of socket programming. now in the same code i also want to check for the network connection availability before each file is transferred. i also want that the files transferred should be transferred according to their numerical sequence. And while the files are being transferred the transfer progress of each file i.e the progress percentage bar should also be visible on the screen.
i will really appreciate if someone can help me with the code. i am posting the code i have written for file transfer.
ClientMain.java
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ClientMain {
private DirectoryTxr transmitter = null;
Socket clientSocket = null;
private boolean connectedStatus = false;
private String ipAddress;
String srcPath = null;
String dstPath = "";
public ClientMain() {
}
public void setIpAddress(String ip) {
this.ipAddress = ip;
}
public void setSrcPath(String path) {
this.srcPath = path;
}
public void setDstPath(String path) {
this.dstPath = path;
}
private void createConnection() {
Runnable connectRunnable = new Runnable() {
public void run() {
while (!connectedStatus) {
try {
clientSocket = new Socket(ipAddress, 3339);
connectedStatus = true;
transmitter = new DirectoryTxr(clientSocket, srcPath, dstPath);
} catch (IOException io) {
io.printStackTrace();
}
}
}
};
Thread connectionThread = new Thread(connectRunnable);
connectionThread.start();
}
public static void main(String[] args) {
ClientMain main = new ClientMain();
main.setIpAddress("10.6.3.92");
main.setSrcPath("E:/temp/movies/");
main.setDstPath("D:/tcp/movies");
main.createConnection();
}
}
(DirectoryTxr.java)
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectoryTxr {
Socket clientSocket = null;
String srcDir = null;
String dstDir = null;
byte[] readBuffer = new byte[1024];
private InputStream inStream = null;
private OutputStream outStream = null;
int state = 0;
final int permissionReqState = 1;
final int initialState = 0;
final int dirHeaderSendState = 2;
final int fileHeaderSendState = 3;
final int fileSendState = 4;
final int fileFinishedState = 5;
private boolean isLive = false;
private int numFiles = 0;
private int filePointer = 0;
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
String dirFailedResponse = "Failed";
File[] opFileList = null;
public DirectoryTxr(Socket clientSocket, String srcDir, String dstDir) {
try {
this.clientSocket = clientSocket;
inStream = clientSocket.getInputStream();
outStream = clientSocket.getOutputStream();
isLive = true;
this.srcDir = srcDir;
this.dstDir = dstDir;
state = initialState;
readResponse(); //starting read thread
sendMessage(request);
state = permissionReqState;
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendMessage(String message) {
try {
sendBytes(request.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Thread to read response from server
*/
private void readResponse() {
Runnable readRunnable = new Runnable() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
} catch (SocketException se) {
System.exit(0);
} catch (IOException io) {
io.printStackTrace();
isLive = false;
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void sendDirectoryHeader() {
File file = new File(srcDir);
if (file.isDirectory()) {
try {
String[] childFiles = file.list();
numFiles = childFiles.length;
String dirHeader = "$" + dstDir + "#" + numFiles + "&";
sendBytes(dirHeader.getBytes("UTF-8"));
} catch (UnsupportedEncodingException en) {
en.printStackTrace();
}
} else {
System.out.println(srcDir + " is not a valid directory");
}
}
private void sendFile(String dirName) {
File file = new File(dirName);
if (!file.isDirectory()) {
try {
int len = (int) file.length();
int buffSize = len / 8;
//to avoid the heap limitation
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
int numRead = 0;
while (numRead >= 0) {
ByteBuffer buf = ByteBuffer.allocate(1024 * 100000);
numRead = channel.read(buf);
if (numRead > 0) {
byte[] array = new byte[numRead];
System.arraycopy(buf.array(), 0, array, 0, numRead);
sendBytes(array);
}
}
System.out.println("Finished");
} catch (IOException io) {
io.printStackTrace();
}
}
}
private void sendHeader(String fileName) {
try {
File file = new File(fileName);
if (file.isDirectory())
return;//avoiding child directories to avoid confusion
//if want we can sent them recursively
//with proper state transitions
String header = "&" + fileName + "#" + file.length() + "*";
sendHeader(header);
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (clientSocket) {
if (outStream != null) {
try {
outStream.write(dataBytes);
outStream.flush();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
private void processBytes(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(respServer) && state == permissionReqState) {
state = dirHeaderSendState;
sendDirectoryHeader();
} else if (message.trim().equalsIgnoreCase(dirResponse) && state == dirHeaderSendState) {
state = fileHeaderSendState;
if (LocateDirectory()) {
createAndSendHeader();
} else {
System.out.println("Vacant or invalid directory");
}
} else if (message.trim().equalsIgnoreCase(fileHeaderRecvd) && state == fileHeaderSendState) {
state = fileSendState;
sendFile(opFileList[filePointer].toString());
state = fileFinishedState;
filePointer++;
} else if (message.trim().equalsIgnoreCase(fileReceived) && state == fileFinishedState) {
if (filePointer < numFiles) {
createAndSendHeader();
}
System.out.println("Successfully sent");
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Going to exit....Error ");
// System.exit(0);
} else if (message.trim().equalsIgnoreCase("Thanks")) {
System.out.println("All files were copied");
}
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean LocateDirectory() {
boolean status = false;
File file = new File(srcDir);
if (file.isDirectory()) {
opFileList = file.listFiles();
numFiles = opFileList.length;
if (numFiles <= 0) {
System.out.println("No files found");
} else {
status = true;
}
}
return status;
}
private void createAndSendHeader() {
File opFile = opFileList[filePointer];
String header = "&" + opFile.getName() + "#" + opFile.length() + "*";
try {
state = fileHeaderSendState;
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
private void sendListFiles() {
createAndSendHeader();
}
}
(ServerMain.java)
public class ServerMain {
public ServerMain() {
}
public static void main(String[] args) {
DirectoryRcr dirRcr = new DirectoryRcr();
}
}
(DirectoryRcr.java)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class DirectoryRcr {
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String dirFailedResponse = "Failed";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
Socket socket = null;
OutputStream ioStream = null;
InputStream inStream = null;
boolean isLive = false;
int state = 0;
final int initialState = 0;
final int dirHeaderWait = 1;
final int dirWaitState = 2;
final int fileHeaderWaitState = 3;
final int fileContentWaitState = 4;
final int fileReceiveState = 5;
final int fileReceivedState = 6;
final int finalState = 7;
byte[] readBuffer = new byte[1024 * 100000];
long fileSize = 0;
String dir = "";
FileOutputStream foStream = null;
int fileCount = 0;
File dstFile = null;
public DirectoryRcr() {
acceptConnection();
}
private void acceptConnection() {
try {
ServerSocket server = new ServerSocket(3339);
socket = server.accept();
isLive = true;
ioStream = socket.getOutputStream();
inStream = socket.getInputStream();
state = initialState;
startReadThread();
} catch (IOException io) {
io.printStackTrace();
}
}
private void startReadThread() {
Thread readRunnable = new Thread() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
sleep(100);
} catch (SocketException s) {
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException i) {
i.printStackTrace();
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void processBytes(byte[] buff) throws InterruptedException {
if (state == fileReceiveState || state == fileContentWaitState) {
//write to file
if (state == fileContentWaitState)
state = fileReceiveState;
fileSize = fileSize - buff.length;
writeToFile(buff);
if (fileSize == 0) {
state = fileReceivedState;
try {
foStream.close();
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Received " + dstFile.getName());
sendResponse(fileReceived);
fileCount--;
if (fileCount != 0) {
state = fileHeaderWaitState;
} else {
System.out.println("Finished");
state = finalState;
sendResponse("Thanks");
Thread.sleep(2000);
System.exit(0);
}
System.out.println("Received");
}
} else {
parseToUTF(buff);
}
}
private void parseToUTF(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(request) && state == initialState) {
sendResponse(respServer);
state = dirHeaderWait;
} else if (state == dirHeaderWait) {
if (createDirectory(message)) {
sendResponse(dirResponse);
state = fileHeaderWaitState;
} else {
sendResponse(dirFailedResponse);
System.out.println("Error occurred...Going to exit");
System.exit(0);
}
} else if (state == fileHeaderWaitState) {
createFile(message);
state = fileContentWaitState;
sendResponse(fileHeaderRecvd);
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Error occurred ....");
System.exit(0);
}
}
private void sendResponse(String resp) {
try {
sendBytes(resp.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean createDirectory(String dirName) {
boolean status = false;
dir = dirName.substring(dirName.indexOf("$") + 1, dirName.indexOf("#"));
fileCount = Integer.parseInt(dirName.substring(dirName.indexOf("#") + 1, dirName.indexOf("&")));
if (new File(dir).mkdir()) {
status = true;
System.out.println("Successfully created directory " + dirName);
} else if (new File(dir).mkdirs()) {
status = true;
System.out.println("Directories were created " + dirName);
} else if (new File(dir).exists()) {
status = true;
System.out.println("Directory exists" + dirName);
} else {
System.out.println("Could not create directory " + dirName);
status = false;
}
return status;
}
private void createFile(String fileName) {
String file = fileName.substring(fileName.indexOf("&") + 1, fileName.indexOf("#"));
String lengthFile = fileName.substring(fileName.indexOf("#") + 1, fileName.indexOf("*"));
fileSize = Integer.parseInt(lengthFile);
dstFile = new File(dir + "/" + file);
try {
foStream = new FileOutputStream(dstFile);
System.out.println("Starting to receive " + dstFile.getName());
} catch (FileNotFoundException fn) {
fn.printStackTrace();
}
}
private void writeToFile(byte[] buff) {
try {
foStream.write(buff);
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (socket) {
if (ioStream != null) {
try {
ioStream.write(dataBytes);
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
ClientMain.java and DirectoryTxr.java are the two classes under client application. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
run the ClientMain.java and ServerMain.java
You can sort an array using Arrays.sort(...)
ie
String[] childFiles = file.list();
Arrays.sort(childFiles);
As I understand it, this will sort the files in natural order, based on the file name.
You can modify this by passing a custom Comparator...
Arrays.sort(childFiles, new Comparator<File>() {...}); // Fill out with your requirements...
Progress monitoring will come down to your requirements. Do you want to see only the overall progress of the number of files, the individual files, a combination of both?
What I've done in the past is pre-iterated the file list, calculated the total number of bytes to be copied and used a ProgressMonitor to display the overall bytes been copied...
Otherwise you will need to supply your own dialog. In either case, you will need use SwingUtilities.invokeLater to update them correctly.
Check out Concurrency in Swing for more details.
Network connectivity is subjective. You could simply send a special "message" to there server and wait for a response, but this only suggests that the message was sent and a recipt was received. It could just as easily fail when you start transfering the file again...