Server-client program using Java socket

Asked 2 years ago, Updated 2 years ago, 83 views

I am working on a program that sends a list of files within C/: from the server when I enter A from the client.

The server code.

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(7777);
            while(true) {
            Socket socket = serverSocket.accept();
            BufferedReader si=new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            PrintWriter so= new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));

            if(si.readLine()=="A"){
                so.println(getDirContent());

            } } else {
                so.println(si.readLine());
            }
             so.flush(); si.close(); so.close(); socket.close();
            }
        } } catch(Exception e) {}

    }
    private static String getDirContent() {
        File dir=new File("C:/");
        String files[]=dir.list();
        List<String> list=Arrays.asList(files);
        return list.toString();
    }

}

The client code.

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket=new Socket("localhost",7777);
            BufferedReader si=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
            PrintWriter so=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
            Scanner ki=new Scanner(System.in);
            so.println(ki.nextLine()); so.flush();
            System.out.println(si.readLine());
            si.close(); so.close(); ki.close(); socket.close();
        } } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

It can be executed, but even if I enter it from the client, the result does not come out properly. What is the problem?

socket

2022-09-22 08:19

1 Answers

si.readLine()=="A" This line Change to "A".equals(si.readLine()

This is because the address value of "A" and the address value of si.readLine() did not match, so false was returned.

The == operator compares the address values of the objects, and equals() compares the contents.

Note that when using the equals method, the constant must be preceded to be safe from null point exception.


2022-09-22 08:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.