简体   繁体   中英

Getting a 'Connection refused: connect' error because parseInt in Java Socket after passing data to the server from client?

I was trying to pass from the client to the server an Integer so in the Server class I could use that integer as a parameter for my fibonacci function. The thing is that the program was running perfectly fine and the connections were well stablished before adding the following lines:

String transformedData = data.toString();
int transformedInt = Integer.parseInt(transformedData);
                
int result = fibonacci(transformedInt); 

So I don't know why I'm getting the error (below) when I pass ANY string from the client to the server

java.net.ConnectException: Connection refused: connect
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:503)
    at java.base/sun.nio.ch.Net.connect(Net.java:492)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
    at java.base/java.net.Socket.connect(Socket.java:648)
    at java.base/java.net.Socket.connect(Socket.java:597)
    at java.base/java.net.Socket.<init>(Socket.java:520)
    at java.base/java.net.Socket.<init>(Socket.java:294)
    at ajHomeWork1/cop2805.Client.main(Client.java:14)

Also, I'm new to the socket programming in java so I really don't know if what I did to transform the byte data to Integer is the proper way to do it for this program

Server class:

public class Server {
        
    static int fibonacci(int numb) // Recursive Fibonacci
    {
        if (numb <= 1)
            return numb;
        return fibonacci(numb-1) + fibonacci(numb-2);
    }
         
        
    
    public static void main(String[] args) {
        
        
        ServerSocket server = null;
        boolean shutdown = false;
        
        
        try {
            server = new ServerSocket(1238);
            System.out.println("Port bound. Accepting Conncetions");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
        
        while(!shutdown) {
            Socket client = null;
            InputStream input = null;
            OutputStream output = null;
            
            try {
                client = server.accept();
                input = client.getInputStream();
                output = client.getOutputStream();
                
                int n = input.read();
                byte[] data = new byte[n];
                String transformedData = data.toString();
                int transformedInt = Integer.parseInt(transformedData);
                
                int result = fibonacci(transformedInt); 
                input.read(data);
                
                String clientInput = new String(data, StandardCharsets.UTF_8);
                clientInput.replace("\n", "");
                System.out.println("Client said " + clientInput);
                
                String response = "Your input was [" + clientInput + "]" + " Fibonacci result of " + transformedInt + " is : " + result;
                output.write(response.length());
                output.write(response.getBytes());
                
                client.close();
                if(clientInput.equalsIgnoreCase("shutdown")) {
                    System.out.println("Shutting down....");
                    shutdown = true;
                }
            }
            
            catch (IOException e) { 
                e.printStackTrace();
                continue;
                
            }
        }

    }
}

And this is the client class:

public class Client {
    
    public static void main(String[] args) {
        System.out.print("Input an int : ");
        BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
        try {
            String userString = userInput.readLine();
            Socket connection = new Socket("127.0.0.1",1238);
            InputStream input = connection.getInputStream();
            OutputStream output = connection.getOutputStream();
            
            output.write(userString.length());
            output.write(userString.getBytes());
            
            int n = input.read();
            byte[] data = new byte[n];
            input.read(data);
            
            String serverResponse = new String(data, StandardCharsets.UTF_8);
            System.out.println("Server said: " + serverResponse);
            
            if(!connection.isClosed())
                connection.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

There are several logic errors in the way that both client and server are treating data. But mishandling of data after the connection is established cannot cause a "Connection refused" error. That error means the new Socket("127.0.0.1",1238) statement in the client is failing before any data can be exchanged. Which means the client is not able to connect to the server at all, either because:

  • the IP/Port is wrong, or there is no server listening on the IP/port.
  • the server's backlog of pending connections is full.
  • a firewall/antivirus is blocking the connection.

Once you address that and can establish a connection correctly, then try something more like the following regarding the data exchange:

Server class:

public class Server {

    static int fibonacci(int numb) // Recursive Fibonacci
    {
        if (numb <= 1)
            return numb;
        return fibonacci(numb-1) + fibonacci(numb-2);
    }

    public static void main(String[] args) {    

        ServerSocket server = null;
        boolean shutdown = false;   

        try {
            server = new ServerSocket(1238);
            System.out.println("Port bound. Accepting Conncetions");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        while (!shutdown) {
            try {
                Socket client = server.accept();
                DataInputStream input = new DataInputStream(new BufferedInputStream(client.getInputStream()));
                DataOutputStream output = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));

                int n = input.readInt();
                byte[] data = new byte[n];
                input.readFully(data);

                String clientInput = new String(data, StandardCharsets.UTF_8);
                clientInput.replace("\n", "");

                System.out.println("Client said " + clientInput);
                String response;

                if (clientInput.equalsIgnoreCase("shutdown"))
                {
                    System.out.println("Shutting down....");
                    response = "Shutting down";
                    shutdown = true;
                }
                else
                {
                    int transformedInt = Integer.parseInt(clientInput);
                    int result = fibonacci(transformedInt); 
                    response = "Your input was [" + clientInput + "] Fibonacci result of " + Integer.toString(transformedInt) + " is : " + Integer.toString(result);
                }

                data = response.getBytes(StandardCharsets.UTF_8);
                output.writeInt(data.length());
                output.write(data, 0, data.length());
                output.flush();

                client.close();
            }
            catch (IOException e) { 
                e.printStackTrace();
            }
        }
    }
}

Client class:

public class Client {
    
    public static void main(String[] args) {
        System.out.print("Input an int : ");
        BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
        try {
            String userString = userInput.readLine();

            Socket connection = new Socket("127.0.0.1", 1238);
            DataInputStream input = new DataInputStream(new BufferedInputStream(connection.getInputStream()));
            DataOutputStream output = new DataOutputStream(new BufferedOutputStream(connection.getOutputStream()));
            
            bytes[] data = userString.getBytes(StandardCharsets.UTF_8);
            output.writeInt(data.length());
            output.write(data, 0, data.length());
            output.flush();
            
            int n = input.readInt();
            data = new byte[n];
            input.readFully(data);
            
            String serverResponse = new String(data, StandardCharsets.UTF_8);
            System.out.println("Server said: " + serverResponse);
            
            connection.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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