在Java中通过IP连接到服务器时出现ConnectException

Posted

技术标签:

【中文标题】在Java中通过IP连接到服务器时出现ConnectException【英文标题】:ConnectException while connecting to server through IP in Java 【发布时间】:2015-07-02 15:25:08 【问题描述】:

我用java编写了一个简单的客户端-服务器程序。当我创建一个像 Socket socket = new Socket("localhost",7000);

这样的套接字时

我能够连接到服务器并将数据(任何控制台输入)传输到服务器,但是当我在 Socket 中传递 localhost Ip(127.0.0.1) 时,就像

 Socket socket = new Socket("127.0.0.1",7000);

我收到以下错误错误:

java.net.ConnectException: Connection refused: connect

为什么我会得到这个。

这是我的服务器端代码

public class SocketServer 

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 

      new SocketServer();

        // TODO code application logic here
    

  public   SocketServer()

       try 
            ServerSocket sSocket = new ServerSocket(7000);
            System.out.println("Server started at: " + new Date());


//Wait for a client to connect
            Socket socket = sSocket.accept();

            //Create the streams
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //Tell the client that he/she has connected
            output.println("You have connected at: " + new Date());

            //Loop that runs server functions
            while(true) 
                //This will wait until a line of text has been sent
                String chatInput = input.readLine();
                System.out.println(chatInput);
            
         catch(IOException exception) 
            System.out.println("Error: " + exception);
        


    

这是我的客户端代码

public class ClientSocket 

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnknownHostException 
        // TODO code application logic here

        new ClientSocket();
    
  public ClientSocket() throws UnknownHostException
    
    //We set up the scanner to receive user input
        Scanner scanner = new Scanner(System.in);

        try 
           //Socket socket = new Socket("localHost",7000);//works Fine
            Socket socket = new Socket("127.0.0.1",7000);//Gives error
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //This will wait for the server to send the string to the client saying a connection
            //has been made.
            String inputString = input.readLine();
            System.out.println(inputString);
            //Again, here is the code that will run the client, this will continue looking for 
            //input from the user then it will send that info to the server.
            while(true) 
                //Here we look for input from the user
                String userInput = scanner.nextLine();
                //Now we write it to the server
                output.println(userInput);
            
         catch (IOException exception) 
            System.out.println("Error: " + exception);
        
    


这是我的 /etc/hosts 文件

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
127.0.0.1       localhost
127.0.0.1       localhost 

【问题讨论】:

你能ping通127.0.0.1吗?你试过telnet吗?可能是您的服务器配置有问题。 是的,我可以ping通 试试这个***.com/questions/14976867/… 【参考方案1】:

您在客户端中使用了错误的构造函数来创建 Socket。

这段代码:

Socket socket = new Socket("127.0.0.1", 7000);

正在尝试将名称 "127.0.0.1" 解析为 DNS 名称。这个构造函数在内部这样做:

InetAddress.getByName(hostname);

如果你想连接到一个 IP 地址,你必须使用这个构造函数:

InetAddress address = InetAddress.getByAddress(new byte[]127,0,0,1);
Socket socket = new Socket(address, 7000)

【讨论】:

看起来你已经在那个端口监听了一些东西。您的服务器代码看起来正确。它将默认接受任何/所有本地地址上的连接。您可以尝试在服务器关闭时远程登录到 127.0.0.1 7000 吗? 抱歉,我发现了问题。您正在使用错误的构造函数创建 Socket 。我已经更新了答案【参考方案2】:

我遇到了类似的问题。在您的代码中进行以下更改

在客户端

InetAddress addr = InetAddress.getByName("127.0.0.1");
Socket socket = new Socket(addr,7000);

在服务器端

ServerSocket sSocket = new ServerSocket();
sSocket.bind(new InetSocketAddress("0.0.0.0", 7000));

@Stefan 也答对了,绑定到0.0.0.0 将允许它监听所有接口

【讨论】:

【参考方案3】:

创建Socket 时,会将其绑定到某个地址。在您的情况下,您将其绑定到localhost,这与127.0.0.1 相同,但地址不同(而localhost 应始终解析为127.0.0.1)。您的应用程序看到连接尝试,但它也看到它不应该侦听该地址,因此它拒绝连接。

尝试将您的服务器套接字绑定到127.0.0.1 甚至0.0.0.0(使用0.0.0.0,您是在告诉它监听所有传入连接(127.0.0.1localhost 和您的 LAN IP 地址/主机名) )。

Here's some more information about this.

看到你的服务器和客户端后,你可以在服务器端尝试以下操作:

ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("127.0.0.1", 7000));

【讨论】:

我已经把我的代码给客户端和服务器你可以回答w.r.t那个。

以上是关于在Java中通过IP连接到服务器时出现ConnectException的主要内容,如果未能解决你的问题,请参考以下文章

TCP-IP 套接字 C:尝试连接到服务器套接字时出现错误地址错误

连接到 IP 时出现错误(套接字失败:EPERM)

Java - 使用 JDBC 连接到在线 MySQL 数据库时出现问题

使用 JSch 从 Java 连接到 SSH 服务器时出现“JSchException:拒绝 HostKey”

Sqoop - 尝试连接到 Oracle DB 服务器时出现 java.lang.NullPointerException

使用私钥连接到服务器时出现pysftp AuthenticationException