I'm a beginner at java and also for socket programming.
This program I've written is aimed to allow p2p file synchronisation between client and server.
When a peer establishes a TCP connection with another peer, both of them will compare the lists of files they possess and proceed to exchange files so that they both have exactly the
same files. A TCP connection must remain open until the peer process is manually terminated at either end of the connection.
I've looked at online tutorials and similar programs to write the code for this program. However, after running the server, the following error is shown on the console when I run the client.
IOException: java.net.ConnectException: Connection timed out: connect
Please advice me on how I could solve the error. Thanks so much in advance!
Here is my code for reference.
Server:
package bdn;
import java.net.*;
import java.io.*;
import java.util.*;
public class MultipleSocketServer extends Thread{
// private Socket connection;
private String TimeStamp;
private int ID;
static int port = 6789;
static ArrayList<File> currentfiles = new ArrayList<File>();
static ArrayList<File> missingsourcefiles = new ArrayList<File>();
public static void main(String[] args)
{
File allFiles = new File("src/bdn/files");
if (!allFiles.exists()) {
if (allFiles.mkdir()) {
System.out.println("Directory is created.");
}
}
//Load the list of files in the directory
listOfFiles(allFiles);
try {
new MultipleSocketServer().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
e.printStackTrace();
}
}
public static void listOfFiles(final File folder){
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listOfFiles(fileEntry);
} else {
//System.out.println(fileEntry.getName());
currentfiles.add(fileEntry.getAbsoluteFile());
}
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(-1);
}
while (listening) {
handleClientRequest(serverSocket);
}
//serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new ConnectionRequestHandler(serverSocket.accept()).run();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket = null;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
System.out.println("Client connected to socket: " + _socket.toString());
try {
ObjectOutputStream oos = new ObjectOutputStream (_socket.getOutputStream());
oos.flush();
oos.writeObject(currentfiles); //sending to client side.
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
syncMissingFiles();
}
@SuppressWarnings("unchecked")
public void syncMissingFiles(){
try {
ObjectInputStream ois = new ObjectInputStream(_socket.getInputStream());
System.out.println("Is the socket connected="+_socket.isConnected());
missingsourcefiles= (ArrayList<File>) ois.readObject();
System.out.println(missingsourcefiles);
//add missing files to current file list.
ListIterator<File> iter = missingsourcefiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
currentfiles.add(temp_file);
}
} catch (IOException e) {
e.printStackTrace();
} catch ( ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
Client:
package bdn;
import java.net.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;
/* The java.io package contains the basics needed for IO operations. */
import java.io.*;
public class SocketClient {
/** Define a port */
static int port = 2000;
static Socket peer_socket = null;
static String peerAddress;
static ArrayList<File> currentfiles = new ArrayList<File>();
static ArrayList<File> sourcefiles = new ArrayList<File>();
static ArrayList<File> missingsourcefiles = new ArrayList<File>();
static ArrayList<File> missingcurrentfiles = new ArrayList<File>();
SocketClient(){}
public static void listOfFiles(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listOfFiles(fileEntry);
} else {
//System.out.println(fileEntry.getName());
currentfiles.add(fileEntry.getAbsoluteFile());
}
}
}
@SuppressWarnings("unchecked")
public static void getListfromPeer() {
try {
ObjectInputStream inList =new ObjectInputStream(peer_socket.getInputStream());
sourcefiles = (ArrayList<File>) inList.readObject();
} catch (ClassNotFoundException e) {
System.err.println("Error in data type.");
}catch (IOException classNot){
System.err.println("Error in data type.");
}
}
public static void compareList1() {
//Compare the source files and current files. If not in current files, add the files to "missingcurrentfiles".
ListIterator<File> iter = sourcefiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
if (!currentfiles.contains(temp_file)) //file cannot be found
{
missingcurrentfiles.add(temp_file);
}
}
}
public static void compareList2() {
//Compare the source files and current files. If not in current files, add the files to "missingsourcefiles".
ListIterator<File> iter = currentfiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
if (!sourcefiles.contains(temp_file)) //file cannot be found
{
missingsourcefiles.add(temp_file);
}
}
}
public static void main(String[] args) {
//Make file lists of the directory in here.
File allFiles = new File("src/bdn/files");
if (!allFiles.exists()) {
if (allFiles.mkdir()) {
System.out.println("Directory is created.");
}
}
/*Get the list of files in that directory and store the names in array*/
listOfFiles(allFiles);
/*Connect to peer*/
try {
new SocketClient().transfer();
//new TcpClient().checkForInput();
} catch (Exception e) {
System.out.println("Failed at main" + e.getMessage());
e.printStackTrace();
}
}
public void transfer(){
getPeerAddress();
// StringBuffer instr = new StringBuffer();
// String TimeStamp;
try {
/** Obtain an address object of the server */
// InetAddress address = InetAddress.getByName(host);
// System.out.println("Address of connected host:"+ address);
/** Establish a socket connection */
Socket connection = new Socket(peerAddress, port);
System.out.println("New SocketClient initialized");
getListfromPeer();
compareList1();
compareList2();
System.out.println(missingcurrentfiles);
System.out.println(missingsourcefiles);
/** Instantiate a BufferedOutputStream object */
// BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
/** Instantiate an ObjectOutputStream*/
ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
oos.flush();
/*
TimeStamp = new java.util.Date().toString();
String process = "Calling the Socket Server on "+ host + " port " + port +
" at " + TimeStamp + (char) 13;
*//** Write across the socket connection and flush the buffer *//*
oos.writeObject(process);
oos.flush();*/
oos.writeObject(missingsourcefiles);
oos.flush();
System.out.println("Missing files in source sent back.");
}
catch (IOException f) {
System.out.println("IOException: " + f);
}
catch (Exception g) {
System.out.println("Exception: " + g);
}
}
public void syncMissingFiles(){
//add missing files to current file list.
ListIterator<File> iter = missingcurrentfiles.listIterator();
File temp_file;
while (iter.hasNext()) {
// System.out.println(iter.next());
temp_file = iter.next();
currentfiles.add(temp_file);
}
}
public static void getPeerAddress() {
// prompt the user to enter the client's address
System.out.print("Please enter the IP address of the client :");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the IP address from the command-line
try {
peerAddress = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read client's IP address!");
System.exit(1);
}
System.out.println("Thanks for the client's IP address, " + peerAddress);
}
}