收到 'Connection refused: connect' 错误,因为在将数据从客户端传递到服务器后 Java Socket 中的 parseInt?

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

我试图从客户端向服务器传递一个 Integer,因此在服务器 class 中,我可以将该整数用作我的斐波那契函数的参数。问题是该程序 运行 非常好,并且在添加以下行之前已经很好地建立了连接:

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

因此,当我将任何字符串从客户端传递到服务器时,我不知道为什么会出现错误(如下)

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)

此外,我是 java 中的套接字编程的新手,所以我真的不知道我将字节数据转换为整数的做法是否适合此程序

服务器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;
                
            }
        }

    }
}

这是客户端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();
        }
    }
}

客户端和服务器处理数据的方式存在一些逻辑错误。但是建立连接后对数据的错误处理不会导致“连接被拒绝”错误。该错误意味着客户端中的 new Socket("127.0.0.1",1238) 语句在可以交换任何数据之前失败。这意味着客户端根本无法连接到服务器,原因可能是:

  • IP/Port不对,或者IP/port没有服务器监听。
  • 服务器积压的待处理连接已满。
  • a firewall/antivirus 正在阻止连接。

一旦你解决了这个问题并且可以正确建立连接,然后尝试更多类似以下关于数据交换的东西:

服务器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();
            }
        }
    }
}

客户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();
        }
    }
}