5 Replies - 234 Views - Last Post: 06 August 2012 - 06:54 AM Rate Topic: -----

#1 kaizerr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 02-August 11

Client-Server menuSelect

Posted 06 August 2012 - 05:54 AM

hello, i've managed client-server log in by using validator input, and process inputs through database. up to that point, everything seems fine, but once i want to create a menu select before proceed to log in, it keep bypassing the whole log in process.

(client.java on line 82 and server.java on line 56)

Server.java

import java.net.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.sql.*;
import javax.sql.*;

public class server{ 
   private static String message = "Hello from your server";  
   private static class ServeClient extends Thread {
      
      private Socket socket;
		byte [ ] buff = new byte[100];	
		int len;						
   
      public ServeClient( Socket s ) { 
         socket = s; 			
      }

      public void run() {
         
         System.out.println("** Server thread started"); 
         String outbuff=new String(message+"\r\n");	
         
         try {
            OutputStream sout = socket.getOutputStream();
            
            InputStream sin = socket.getInputStream();
            	
            sout.write(outbuff.getBytes());
            System.out.println("** Message sent: "+outbuff); 
            
            
            //set par for phpmyadmin login
			String url="jdbc:mysql://localhost/";
			String dblogin="test";
			String usr="root";
			String pwd="";
			
			//set input and scanner
            String username, password,email,mainMenu;
            Scanner sc;

/********* Here: put all changes to read, send and process messages here ********/
            len = sin.read(buff);
            message = new String(buff, 0, len);
            System.out.println("Message received: " + message);

			outbuff=new String("1. Login"+"\r\n"+"2. Register"+"\r\n");
			sout.write(outbuff.getBytes());
            System.out.println("** Message sent: "+outbuff); 

			len = sin.read(buff);
            message = new String(buff, 0, len);
            
            //here comes the problem
            if(message=="1" || message=="login" || message=="Login"){
            sc = new Scanner(message).useDelimiter(":"); 		//initialise Scanner
            
            
            if (sc.next().equals("L") ) {   // L:username:password	//get next part
            	
         		username = sc.next();				//get next part
         		password = sc.next();				//get next part
         		email = sc.next();					//get next part
         		//System.out.println("Login:\nuser = "+username+" password = "+password+" email = "+email);
         		//System.out.println("processing...");
         		
         		//validator param
         		//username
         		Pattern uPat = Pattern.compile("[A-Za-z]{0,12}");
				Matcher uM = uPat.matcher(username);
				boolean uCheck = uM.matches();
				
				//password
         		Pattern pPat = Pattern.compile("[A-Za-z]{6,18}");
				Matcher pM = pPat.matcher(password);
				boolean pCheck = pM.matches();
				
				//email
				Pattern ePat = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{0,44})$");
				Matcher eM = ePat.matcher(email);
				boolean eCheck = eM.matches();
				
				System.out.println("\n");
		
         		//filter input
         		if(uCheck==false){
					outbuff=new String("U"+"\r\n");		//error login name
				}
				
				else if(pCheck==false){
					outbuff=new String("U"+"\r\n");		//error login password
				}
				
				else if(uCheck==false){
					outbuff=new String("U"+"\r\n");		//error login email
				}
         		
         		else{
         			System.out.println("**Processing");
         			try{
         				Connection conn=DriverManager.getConnection(url+dblogin,usr,pwd);
						Statement stat=conn.createStatement();
						ResultSet res=stat.executeQuery("SELECT * FROM login WHERE userName='"+username+"' AND password='"+password+"' AND eMail='"+email+"'");
					
						//set "i" as rules for log in incld. total row(s)
						//int i=res.getRow();
						res.last();
						
					
						if(res.getRow()==1){
							outbuff=new String("K"+"\r\n");		//OK, no error
							sout.write(outbuff.getBytes());
        					System.out.println("** Message sent: "+outbuff);
						}
				
						else{
							outbuff=new String("U"+"\r\n");     //error, no such id,pass,email exists
							sout.write(outbuff.getBytes());
        					System.out.println("** Message sent: "+outbuff);
						}
				
         				res.close();
						conn.close();
         			
         			}
         			         			
         			catch(Exception ex){
						ex.printStackTrace();
					}
         		}
            } 
            	//m
			} 
         }
         catch (IOException x ) {
         	System.out.println("Problem encountered -> " + x );
         }      
         System.out.println("** Server thread finished"); 
      }

   }

   private static int getPort()
   {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      try {
         int p = 0;
         boolean incorrect;
         do {
            System.out.print("Give port: ");
            try {
               p = Integer.parseInt(in.readLine());
               try {
                  new InetSocketAddress("0.0.0.0",p);
                  incorrect = false;
               }
               catch ( IllegalArgumentException x ) {
                  System.out.println("Port out of range");
                  incorrect = true;
               }
            }
            catch ( NumberFormatException x ) {
               System.out.println("Port should be integer");
               incorrect = true;
            }
         } while ( incorrect );
         return p;
      }
      catch (IOException x ) {
         throw new Error("unexpected exception -> " + x);
      }
   }
    
   public static void main( String[] args ) 
   {
      int port = getPort();
      try {
         ServerSocket server = new ServerSocket(port,5);
         System.out.println("ServerSocket created"); 
         while ( true ) {
            System.out.println("Ready to acccept"); 
            Socket socket = server.accept();
            System.out.println("Connection accepted and server thread started"); 
            Thread t = new ServeClient(socket);
            t.start();
         }
      }
      catch (IOException x ) {
         System.out.println("Sockets problem: " + x );
      }
   }

}








Client.java


import java.net.*;
import java.io.*;
import java.util.*;


public class client {
   static BufferedReader in;
   private static InetSocketAddress readHostAndPort()
   {
      in = new BufferedReader(new InputStreamReader(System.in));
      try {
         System.out.print("Give host: ");
         String h = in.readLine();
         int p = 0;
         boolean incorrect;
         InetSocketAddress addr = null;
         do {
            System.out.print("Give port: ");
            try {
               p = Integer.parseInt(in.readLine());
               try {
                  addr = new InetSocketAddress(h,p);
                  incorrect = false;
               }
               catch ( IllegalArgumentException x ) {
                  System.out.println("Port out of range");
                  incorrect = true;
               }
            }
            catch ( NumberFormatException x ) {
               System.out.println("Port should be integer");
               incorrect = true;
            }
         } while ( incorrect );
            return addr;
      }
      catch (IOException x ) {
         throw new Error("unexpected exception -> " + x);
      }
   }
    
   public static void main(String[] args) 
   {
      byte [] buff = new byte[100];	
      int len = 0;					
      Socket socket = new Socket();
      String message = null;	
	  String outbuff = null;	

              
      InetSocketAddress addr = readHostAndPort();
      if ( addr.isUnresolved() ) {
         System.out.print("Socket address unresolved - "); 
         System.out.println("bad host = " + addr.getHostName() );
      }
      else {
         System.out.print("Socket address resolved as "); 
         System.out.println(addr.getHostName() + "/" + addr.getPort());
         try {
            System.out.println("Attempting to connect"); 
            socket.connect(addr);
            System.out.println("Connection made to " + 
                               socket.getInetAddress().getHostName()); 
            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();
            
            len = sin.read(buff);
            message = new String(buff,0, len);
			System.out.println("Message from server is >" + message + "<");

			String username, password, email, mainMenu;
			                        
/******HERE: put all changes to read, send and process messages here ********/
			outbuff = new String("Request mainMenu");
            sout.write(outbuff.getBytes( ));
            System.out.println("**Message sent: "+outbuff); 

            len = sin.read(buff);
            message = new String(buff,0, len);
			System.out.println("Message from server is >" + message + "<");
			
			///***here the menu selection***
			System.out.print("menuSelect: ");
    	    String m1 = in.readLine();
    	    outbuff = new String(m1);
    	    sout.write(outbuff.getBytes( ));
    	    System.out.println("**Message sent: "+outbuff);
			
//			outbuff = new String("L:lee:1234");     // fixed user name and password
	        System.out.print("type user name or type 'X' to quit: ");
    	    String u = in.readLine();
    	    if (u.equals("O")) {
    	    	System.out.println("Log out"+"\r\n"); 
    	    	return;
    	    }
    	    else if(u.equals("X")){
    	    	System.exit(1);
    	    }
			System.out.print("Password: ");
    	    String p = in.readLine();
			outbuff = new String("L:"+u+":"+p);
            
            System.out.print("Email: ");
    	    String e = in.readLine();
			outbuff = new String("L:"+u+":"+p+":"+e);
			
            sout.write(outbuff.getBytes( ));
            System.out.println("**Message sent: "+outbuff);
            
            len = sin.read(buff);
            message = new String(buff,0, len);
			System.out.println("Message from server is >" + message + "<");
         
         }
         catch (IOException x ) {
            System.out.println("Problem encountered -> " + x );
         }
         }
	}
}









Is This A Good Question/Topic? 0
  • +

Replies To: Client-Server menuSelect

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Client-Server menuSelect

Posted 06 August 2012 - 06:21 AM

if(message=="1" || message=="login" || message=="Login"){

You can't compare String using the == operator
You'll have to use the String class equals() method

sure that the address in the server code of your contants "Login", "login" and "1" is not the same as the object message

This post has been edited by pbl: 06 August 2012 - 06:24 AM
Reason for edit:: String not Strin

Was This Post Helpful? 0
  • +
  • -

#3 kaizerr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 02-August 11

Re: Client-Server menuSelect

Posted 06 August 2012 - 06:27 AM

View Postpbl, on 06 August 2012 - 06:21 AM, said:

if(message=="1" || message=="login" || message=="Login"){

You can't compare String using the == operator
You'll have to use the String class equals() method

sure that the address in the server code of your contants "Login", "login" and "1" is not the same as the object message


okay sir, i've edit my server file as

sc = new Scanner(message);
//here comes the problem
if(message.equals("login")){



but it still give the same result. please enlight me.

**sorry for my bad english and poor knowledge in java :(
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Client-Server menuSelect

Posted 06 August 2012 - 06:31 AM

add a System.out.println(">" + message + "<");
so will se exactly what is in message
Was This Post Helpful? 0
  • +
  • -

#5 kaizerr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 02-August 11

Re: Client-Server menuSelect

Posted 06 August 2012 - 06:42 AM

View Postpbl, on 06 August 2012 - 06:31 AM, said:

add a System.out.println(">" + message + "<");
so will se exactly what is in message


thanks, i got the result as ">login<" but i still dont have any idea how to process it in my if else condition.

View Postkaizerr, on 06 August 2012 - 06:38 AM, said:

View Postpbl, on 06 August 2012 - 06:31 AM, said:

add a System.out.println(">" + message + "<");
so will se exactly what is in message


thanks, i got the result as ">login<" but i still dont have any idea how to process it in my if else condition.


my apologies sir, i found my mistake is that i forget to put my len and new string param. thank you very much.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Client-Server menuSelect

Posted 06 August 2012 - 06:54 AM

No problem. Glad we could help
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1