1

我是 Java 的初学者,也是套接字编程的初学者。

我编写的这个程序旨在允许客户端和服务器之间的 p2p 文件同步。

当一个对等体与另一个对等体建立 TCP 连接时,他们都会比较他们拥有的文件列表并继续交换文件,以便他们拥有完全相同的文件。TCP 连接必须保持打开状态,直到在连接的任一端手动终止对等进程。

我查看了在线教程和类似程序来编写该程序的代码。但是,运行服务器后,当我运行客户端时,控制台上会显示以下错误。

IOException: java.net.ConnectException: Connection timed out: connect

请告诉我如何解决该错误。提前非常感谢!

这是我的代码供参考。

服务器:

    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();
            }
        }


    }
}

客户:

   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);

      }
}
4

1 回答 1

0

据我所知,我不是专家,您将服务器设置为侦听端口 6789,而您的客户端连接到端口 2000。它们都应该在同一个端口上工作。

尝试在您的客户端构造函数中执行以下操作。

    SocketClient(String servername){
        //while port is same as server port
        peer_socket = new Socket(servername, port);
    }

如果您在本地工作,您可以将 main 中的 servername 设置为“localhost”

另外,我建议您验证您正在使用的端口没有被您机器上现有的任何防火墙阻止。

于 2013-05-01T23:23:34.413 回答