简体   繁体   中英

JAVA Client - Server - reading Object from ObjectInputStreamReader

I am trying to make user authentication, I have manage to send User object to server and check details on the server but I have the problem the send back the object to client proving loggin was successful. Here is attached file, it is a bit messy as I was trying to experiment with it:

Client

    public class Requester {
        Socket requestSocket;
        ObjectOutputStream out;
        ObjectInputStream in;
        String message="";
        String message2 = "";

        String login="";
        String password="";

        String ipaddress;
        Scanner stdin;
        Requester(){}
        void run()
        {
            stdin = new Scanner(System.in);
            try{
                //1. creating a socket to connect to the server
                User newUser = new User();
                User receivedUser = new User();

                boolean authenticated = false;

                System.out.println("Please Enter your IP Address");
                ipaddress = stdin.next();
                requestSocket = new Socket(ipaddress, 2004);
                System.out.println("Connected to "+ipaddress+" in port 2004");
                //2. get Input and Output streams
                out = new ObjectOutputStream(requestSocket.getOutputStream());
                out.flush();
                out.reset();
                in = new ObjectInputStream(requestSocket.getInputStream());
                System.out.println("Hello");
                //3: Communicating with the server

                do{
                    try
                    {       
                            message = (String)in.readObject();
                            System.out.println(message);                        

                            System.out.print("Please enter username: ");
                            login = stdin.next();
                            newUser.setName(login);
                            System.out.println(login);

                            System.out.print("Please enter password: ");
                            password = stdin.next();
                            newUser.setPassword(password);
                            System.out.println(password);

                            //in = new ObjectInputStream(requestSocket.getInputStream());
                            sendMessage(newUser);

                            message = (String)in.readObject();
                            receivedUser = (User)in.readObject();
                            //System.out.println(message);
                            //receivedUser = (User)in.readObject();

                            /*if(receivedUser.getAthentication() == true) {
                                System.out.println("CLIENT LOGIN");
                            } else {
                                System.out.println("CLIENT FAILED");
                            }*/
                    }
                    catch(ClassNotFoundException classNot)
                    {
                        System.err.println("data received in unknown format");
                    }
                }while(!message.equals("bye"));
            }
            catch(UnknownHostException unknownHost){
                System.err.println("You are trying to connect to an unknown host!");
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
            finally{
                //4: Closing connection
                try{
                    in.close();
                    out.close();
                    requestSocket.close();
                }
                catch(IOException ioException){
                    ioException.printStackTrace();
                }
            }
        }
        void sendMessage(User newUser)
        {
            try{
                out.writeObject(newUser);
                out.flush();
                //System.out.println("client>" + msg);
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
        public static void main(String args[])
        {
            Requester client = new Requester();
            client.run();
        }
    }

Server

    public class EchoServer {
      static List<User> users = new ArrayList<User>();

      public static void main(String[] args) throws Exception {

        User user1 = new User("john", "test1");
        users.add(user1);   
        User user2 = new User("paul", "test2");
        users.add(user2);   
        User user3 = new User("martin", "test3");
        users.add(user3);

        ServerSocket m_ServerSocket = new ServerSocket(2004,10);
        int id = 0;
        while (true) {
          Socket clientSocket = m_ServerSocket.accept();
          ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
          cliThread.start();
        }
      }
    }

    class ClientServiceThread extends Thread {
      Socket clientSocket;
      String message, login;
      int clientID = -1;
      boolean running = true;


      ObjectOutputStream out;
      ObjectInputStream in;

      EchoServer list = new EchoServer();

      ClientServiceThread(Socket s, int i) {
        clientSocket = s;
        clientID = i;
      }

      void sendMessage(String msg)
        {
            try{
                out.writeObject(msg);
                out.flush();
                out.reset();
                System.out.println("client> " + msg);
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }

      void sendUser(User usrObj)
        {
          try {
              out.writeObject(usrObj);
              out.flush();
              out.reset();
              System.out.println("clent> " + "User Object Received");
          } 
          catch(IOException ioException) {
              ioException.printStackTrace();
          }
        }

      public void run() {
        User newUser = new User();
        User userAuthen = new User();

        boolean userAuthenticated = false;

        System.out.println("Accepted Client : ID - " + clientID + " : Address - "
            + clientSocket.getInetAddress().getHostName());
        try 
        {
            out = new ObjectOutputStream(clientSocket.getOutputStream());
            out.flush();
            out.reset();
            in = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Accepted Client : ID - " + clientID + " : Address - "
                    + clientSocket.getInetAddress().getHostName());

            sendMessage("Connection successful\n");
            do{
                try
                {               
                    //message = (String)in.readObject();
                    //System.out.println("client>"+clientID+"  "+ message);
                    //if (message.equals("bye"))
                    newUser = (User)in.readObject();

                    for(User userObj : list.users) {
                        if(userObj.getName().equals(newUser.getName())) {
                            userAuthenticated = true;
                            userAuthen.setAthentication(userAuthenticated);
                        }
                    }

                    /*if(userAuthenticated == false) {
                        sendMessage("Login Incorrect!");
                        sendMessage("FALSE");
                    }*/ 
                    if(userAuthenticated == true) {
                        sendMessage("Login Correct\n");
                        sendMessage("TRUE");

                        sendUser(userAuthen);
                    }
                    if(userAuthenticated == false) {
                        sendMessage("Login Failed\n");
                        sendMessage("FALSE");
                    }
                }
                catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                }

                //sendMessage("server got the following: "+newUser.getName());
                //sendMessage("server got the following: "+newUser.getPassword());
                userAuthenticated = false;
            }while(running);

            System.out.println("Ending Client : ID - " + clientID + " : Address - "
                    + clientSocket.getInetAddress().getHostName());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }


    User

    public class User implements Serializable{
        String name = "";
        String password = "";

        boolean userAuthenticated = false;

        User(String name, String password) {
            this.name = name;
            this.password = password;
        }

        User(){}

        public void setName(String name) {
            this.name = name;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public void setAthentication(boolean userAuthenticated) {
            this.userAuthenticated = userAuthenticated;
        }

        public String getName() {
            return name;
        }

        public String getPassword() {
            return password;
        }

        public boolean getAthentication() {
            return userAuthenticated;
        }
    }

You should be getting ClassCastException, because you send 2 String objects before the User object, but you read only 1 String object before the User object.

Remove the line sendMessage("TRUE"); and it will work.

PS: You may also remove sendMessage("FALSE");

BTW: If you have a Serializable object you should have serialVersionUID to ensure the object version is the same on both sides. Once you make any change, you should also change the version number.

BR, Zsolt

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