简体   繁体   English

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

[英]Socket programming, multithreaded programming. Error: IOException: java.net.ConnectException: Connection timed out: connect

I'm a beginner at java and also for socket programming. 我是Java和套接字编程的初学者。

This program I've written is aimed to allow p2p file synchronisation between client and server. 我编写的该程序旨在允许客户端和服务器之间的p2p文件同步。

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. 当一个对等方与另一个对等方建立TCP连接时,他们两个都将比较他们拥有的文件列表并继续交换文件,以便它们都具有完全相同的文件。 A TCP connection must remain open until the peer process is manually terminated at either end of the connection. TCP连接必须保持打开状态,直到在连接的任一端手动终止对等进程为止。

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

      }
}

From what I've noticed, and I'm not an expert, you set your server to listen on port 6789 while your client connect to port 2000. They should both work on the same port. 据我所知,我不是专家,您将服务器设置为在客户端连接到端口2000时侦听端口6789。它们都应在同一端口上工作。

Try do the following in your client constructor. 尝试在客户端构造函数中执行以下操作。

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

You can set servername in your main to be "localhost" in case you are working locally 您可以在主服务器中将服务器名设置为“ localhost”,以防在本地工作

Also, I would recommand to verify the port you are working on is not blocked by any firewall existing on your machine. 另外,我建议您检查正在使用的端口是否未被计算机上现有的防火墙阻止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 线程“ main”中的异常java.net.ConnectException:连接被拒绝:connect套接字编程Java - Exception in thread “main” java.net.ConnectException: Connection refused: connect Socket Programming Java 休息客户端 java.net.ConnectException:连接超时:连接 - Rest client java.net.ConnectException: Connection timed out: connect java.net.ConnectException消息:连接超时:连接 - java.net.ConnectException MESSAGE: Connection timed out: connect java.net.ConnectException:连接超时:使用路由器连接 - java.net.ConnectException: Connection timed out: connect, using router java.net.ConnectException:连接超时:在Eclipse中连接 - java.net.ConnectException: Connection timed out: connect in Eclipse SocketChannel-java.net.ConnectException:连接超时:connect - SocketChannel - java.net.ConnectException: Connection timed out: connect java.net.ConnectException:连接超时:连接? - java.net.ConnectException :connection timed out: connect? java.net.ConnectException:连接超时:JAVA 中的连接错误和 .NET 中的相同逻辑工作正常 - java.net.ConnectException: Connection timed out: connect error in JAVA and same logic working fine in .NET HTTP传输错误:java.net.ConnectException:连接超时:在Soap ws客户端中连接 - HTTP transport error: java.net.ConnectException: Connection timed out: connect in Soap ws client java.net.ConnectException:连接超时:连接到远程数据库的连接错误 - java.net.ConnectException: Connection timed out: connect error connecting to remote database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM