martes, 28 de mayo de 2019

MMORPG --> Part 2 - Cliente

Ya con un tiempo de espera por fin aquí daremos seguimiento al mmorpg, espero les sea de ayuda.

Por ahora veremos un login sencillo con no mas que un user, password y su respectivo aceptar entre otras cosas mas.

La opción final quedará de la siguiente manera.


Cual será la función, bueno.
 1.- El usuario inicia su aplicación.
 2.- El cliente se conecta con el servidor
 3.- El servidor crea un thread para el cliente nuevo
 4.- El cliente ingresa su usuario y contraseña
 5.- La aplicación del cliente cifra la contraseña
 6.- El usuario envía la petición al servidor
 7.- El servidor valida el usuario y contraseña del cliente, re
torna true o false [ 1, 0 ]
 8.- Si el usuario no fue logeado correctamente corrige usuario o contraseña según sea el caso
 9.- Muestra mensaje de satisfacción Bienvenido.

Sera necesaria la siguiente estructura



De esta manera se queda la estructura del proyecto del lado del cliente por el momento se seguiran agregando más módulos con formeavance el mismo.

El código de cada uno de ello queda de la siguente manera.
                        import com.inovania.cliente.main.Principal;
                        import java.io.DataInputStream;
                        import java.io.DataOutputStream;
                        import java.io.IOException;
                        import java.net.Socket;

                        public class Connections{
                            private final String IP_SERVER = "localhost";
                            public DataInputStream entrada_1 = null;
                            public DataInputStream entrada_2 = null;
                            DataOutputStream salida = null;
                            
                            Socket socket_1 = null;
                            Socket socket_2 = null;
                            String nombreCliente = "";
                            
                            Principal app;
                            
                            public Connections( Principal app ){
                                this.app = app;
                            }
                            
                            public void conexion(){
                                try{
                                    socket_1 = new Socket( IP_SERVER, 5555 );
                                    socket_2 = new Socket( IP_SERVER, 4445 );
                                    entrada_1 = new DataInputStream( socket_1.getInputStream() );
                                    entrada_2 = new DataInputStream( socket_2.getInputStream() );
                                    salida = new DataOutputStream( socket_1.getOutputStream() );
                                    app.init();
                                }catch( IOException ioe ){
                                    System.err.println( "error en la conexion:[ " + ioe.getMessage() + " ]" );
                                }
                            }
                            public void flujo( int opcion,String msg ){
                                try{
                                    salida.writeInt( opcion );
                                    salida.writeUTF(msg);
                                }catch( IOException e ){
                                    System.err.println(e.getMessage());
                                }
                            }
                            public void login( String usr ){
                                try {
                                    salida.writeInt( -1000 );
                                    salida.writeUTF(usr);
                                    if( entrada_1.readInt() == 0 ){
                                        app.messageDialog("eNoLogin");
                                    }else{
                                        app.messageDialog("isLogin");
                                    }
                                } catch (IOException ex) {
                                    System.err.println( ex.getMessage() );
                                }
                            }
                        }
                    
      
                        import com.inovania.cliente.utils.TypeMsg;
                        import java.util.ArrayList;
                        import java.util.List;
                        import static javax.swing.JOptionPane.ERROR_MESSAGE;
                        import static javax.swing.JOptionPane.INFORMATION_MESSAGE;

                        public class Mensajes {
                            public List getMensajes(){
                                List rtn = new ArrayList<>();
                                TypeMsg elem;
                                
                                elem = new TypeMsg("Falta el usuario", ERROR_MESSAGE, "eLoginUser","Usuario");
                                rtn.add(elem);
                                
                                elem = new TypeMsg("Falta el Password", ERROR_MESSAGE, "eLoginPass","Password");
                                rtn.add(elem);
                                
                                elem = new TypeMsg( "Felicidades", INFORMATION_MESSAGE, "isLogin", "Exito" );
                                rtn.add( elem );
                                
                                elem = new TypeMsg( "Usuario o contraseña incorrecta", ERROR_MESSAGE, "eNoLogin", "Credenciales invalid" );
                                rtn.add( elem );
                                
                                return rtn;
                            }
                        }
                    
                        import com.inovania.cliente.controller.Connections;
                        import com.inovania.cliente.controller.Mensajes;
                        import com.inovania.cliente.utils.TypeMsg;
                        import com.inovania.cliente.mmorpg.autenticacion.Autorized;
                        import java.awt.Cursor;
                        import java.awt.Desktop;
                        import java.awt.event.ActionEvent;
                        import java.awt.event.ActionListener;
                        import java.awt.event.KeyAdapter;
                        import java.awt.event.KeyEvent;
                        import java.awt.event.MouseEvent;
                        import java.awt.event.MouseListener;
                        import java.io.IOException;
                        import java.net.URI;
                        import java.net.URISyntaxException;
                        import java.util.List;
                        import javax.swing.JButton;
                        import javax.swing.JFrame;
                        import javax.swing.JLabel;
                        import javax.swing.JOptionPane;
                        import javax.swing.JPasswordField;
                        import javax.swing.JTextField;
                        public class Principal extends JFrame implements ActionListener, MouseListener{
                            JTextField txtUsr;
                            JLabel lblUsr; 
                            JLabel lblPss; 
                            JLabel lblNotLogin;
                            JPasswordField txtPss;
                            JButton btnAceptar;
                            Autorized auth;
                            Connections con;
                            
                            public Principal(){
                                auth = new Autorized();
                                con = new Connections(this);
                                con.conexion();
                            }
                            public static void main(String[] args) {
                                Principal app = new Principal();
                            }
                            public void init() {
                                this.setTitle( "Inovania Game");
                                this.setLayout(null);
                                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                this.setSize(330, 150);
                                this.setLocationRelativeTo(null);
                                
                                lblUsr = new JLabel( "Usuario: " );
                                lblUsr.setBounds( 5,5,50,25);
                                this.add(lblUsr);
                                
                                txtUsr = new JTextField();
                                txtUsr.setBounds( 65,5,140,25 );
                                txtUsr.addKeyListener(new KeyAdapter(){
                                    @Override
                                    public void keyTyped( KeyEvent e ){
                                        if( e.getKeyChar() == '&' ){
                                            e.consume();
                                        }
                                    }
                                });
                                this.add( txtUsr );
                                
                                lblUsr = new JLabel( "Password: " );
                                lblUsr.setBounds( 5,30,50,25);
                                this.add(lblUsr);
                                
                                txtPss = new JPasswordField();
                                txtPss.setBounds( 65, 30, 140, 25 );
                                txtPss.addKeyListener(new KeyAdapter(){
                                    @Override
                                    public void keyTyped( KeyEvent e ){
                                        if( txtPss.getText().trim().length() >= 8 ){
                                            e.consume();
                                        }
                                    }
                                });
                                this.add( txtPss );
                                
                                lblNotLogin = new JLabel( "Create Account");
                                lblNotLogin.addMouseListener(this);
                                lblNotLogin.setCursor( new Cursor( Cursor.HAND_CURSOR ) );
                                lblNotLogin.setName("notLogin");
                                lblNotLogin.setBounds( 5,55,100,25);
                                
                                this.add( lblNotLogin );
                                
                                
                                btnAceptar = new JButton("Aceptar");
                                btnAceptar.setBounds( 210, 5, 95, 50 );
                                btnAceptar.setActionCommand("login");
                                btnAceptar.addActionListener(this);
                                this.add( btnAceptar );
                                
                                txtUsr.setNextFocusableComponent(txtPss);
                                txtPss.setNextFocusableComponent(btnAceptar);
                                btnAceptar.setNextFocusableComponent(txtUsr);
                                
                                this.setVisible(true);
                            }

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                if( e.getActionCommand().equals( "login" ) ){
                                    String usuario = txtUsr.getText();
                                    String passwor = txtPss.getText().trim();
                                    if( usuario.equals("")){
                                        messageDialog("eLoginUser");
                                        return;
                                    }
                                    if( passwor.equals("") ){
                                        messageDialog("eLoginPass");
                                        return;
                                    }
                                    String password = auth.encriptaPassword(passwor);
                                    con.login(usuario + "&" + password);
                                }    
                            }
                            
                            @Override
                            public void mouseClicked(MouseEvent e) {
                                if( e.getSource() == lblNotLogin ){
                                    try{
                                        if( Desktop.isDesktopSupported() ){
                                            Desktop dt = Desktop.getDesktop();
                                            if( dt.isSupported( Desktop.Action.BROWSE ) ){
                                                dt.browse( new URI( "www.inovania.blogspot.com" ) );
                                            }
                                        }
                                    }catch( IOException | URISyntaxException x ){
                                        System.err.println( x.getMessage() );
                                    }
                                }
                            }

                            @Override public void mousePressed(MouseEvent e) {}
                            @Override public void mouseReleased(MouseEvent e) {}
                            @Override public void mouseEntered(MouseEvent e) {}
                            @Override public void mouseExited(MouseEvent e) {}
                            
                            public void messageDialog(Object... msg){
                                Mensajes m = new Mensajes();
                                List mts = m.getMensajes();
                                boolean msgShow = false;
                                for( TypeMsg tm : mts ){
                                    if( tm.getClave().equals( msg[ 0 ] ) ){
                                        JOptionPane.showMessageDialog(
                                                null,
                                                tm.getMsg(),
                                                tm.getTitle(),
                                                tm.getTipo()
                                        );
                                        msgShow = true;
                                        break;
                                    }
                                }
                                if( !msgShow ){
                                    JOptionPane.showMessageDialog(
                                            null,
                                            msg[ 0 ].toString(),//mensaje
                                            (msg.length>1)?msg[ 1 ].toString():"",//titulo
                                            (msg.length>2)?Integer.parseInt( msg[ 2 ].toString() ):JOptionPane.INFORMATION_MESSAGE//tipo
                                    );
                                }
                            }
                        }
                    
                        public class TypeMsg{
                            private String msg;
                            private int tipo;
                            private String clave;
                            private String title;
                            
                            public TypeMsg(String msg, int tipo, String clave, String title) {
                                this.msg = msg;
                                this.tipo = tipo;
                                this.clave = clave;
                                this.title = title;
                            }

                            /**
                             * @return the msg
                             */
                            public String getMsg() {
                                return msg;
                            }

                            /**
                             * @return the tipo
                             */
                            public int getTipo() {
                                return tipo;
                            }

                            /**
                             * @return the clave
                             */
                            public String getClave() {
                                return clave;
                            }
                            /**
                             * @return the title
                             */
                            public String getTitle(){
                                return title;
                            }
                        }
                    

Sin mas por el momento es todo por hoy espero sus comentarios al respecto. No olvides comentar, suscribirte y seguirme para poder continuar con este proyecto hasta el final.


Nos leemos pronto.

No hay comentarios:

Publicar un comentario