简体   繁体   中英

ConnectException while connecting to server through IP in Java

I have written a simple Client-Server program in java. when i create a socket like
Socket socket = new Socket("localhost",7000);

I am able to connect to the server and transfer the data(any console input) to the Server but when i pass localhost Ip(127.0.0.1) in the Socket like

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

I get the following error Error:

java.net.ConnectException: Connection refused: connect

Why i am getting this.

Here is my server side Code

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


    }

Here is my client side Code

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

}

Here is my /etc/hosts file

# 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 

When you create a Socket , you bind it to a certain address. In your case, you bound it to localhost , which is the same as 127.0.0.1 but not the same address (while localhost should always resolve to 127.0.0.1 ). Your application sees the connection attempt, but it also sees that it should not listen on that address so it refuses the connection.

Try binding your server socket to 127.0.0.1 or even 0.0.0.0 (with 0.0.0.0 , you're telling it to listen to all incoming connections ( 127.0.0.1 , localhost and your LAN IP address/hostname)).

Here's some more information about this.

After seeing your server and client, you could try the following on the server side:

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

I faced Similar problem. Make following Changes in your Code

At Client Side

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

At Server Side

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

@Stefan has also answered right,binding to 0.0.0.0 will allow it to listen to all interfaces

You're using the wrong constructor to create the Socket in the client.

This code:

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

Is trying to resolve the name "127.0.0.1" as a DNS name. This constructor is internally doing this:

InetAddress.getByName(hostname);

If you want to connect to an IP address you have to use this constructor:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM