java - 套接字编程、多线程编程。错误 : IOException: java.net.ConnectException:连接超时:连接

标签 java sockets client-server p2p

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

      }
}

最佳答案

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

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

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

如果您在本地工作,您可以将 main 中的服务器名称设置为“localhost”

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

关于java - 套接字编程、多线程编程。错误 : IOException: java.net.ConnectException:连接超时:连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16187086/

相关文章:

Java后端和JavaScript前端,如何加入?

java - 即使我安装了 Java 8,Yosemite 也仅识别 1.6.0.jdk。我无法修改 java_home

java - Tomcat-servlet-api.jar 是否加载到类路径?

c - 如何完全破坏C中的套接字连接

java - 将套接字对象传递给 Android 上的另一个 Activity

c# - 影院预约系统架构

java - 如果是字符串,应该如何使用同步?

java - 如何在 Google map 中创建自定义 map ?

java - BufferedReader、StreamWriter 崩溃

java WS 客户端-服务器与证书的通信,我应该使用什么框架/api?