2 Replies - 374 Views - Last Post: 01 January 2012 - 03:21 PM Rate Topic: -----

#1 Hooor  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 86
  • Joined: 26-May 11

connection between my client and server seems as it is not working

Posted 01 January 2012 - 01:43 PM

high everyone
I am writing java code program to make simple Store program using client server
the client: have interfaces to ask what he wants from the server
the server: should listen to client orders and perform it then return answer

THE PROBLEM is in the compilation the program does not have any problem but when i run it I got
null pointer exception
it seems like the server has not receive any order and the client didnot get any answer

the null exception appears here in the serverProcessor class



StringTokenizer tokenizer = new StringTokenizer(name,"_");
        	name=tokenizer.nextToken();
        c=new Customer(name);
        store.enter(c); // here is the problem[/center][/size]



here is all classes of my program:

package mall;

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;


public class Client1 {

	public static String host = "localhost";
	public static int port = 1237;
	public static String fromServer = "";
	public static Socket clientSocket = null;
	public static PrintWriter out = null;
	public static BufferedReader in = null;
	public static Scanner scan=null;
	public static boolean b=true;
	public static void main(String[] args) {
		
		 try{
			  clientSocket = new Socket(host, port);
			  out = new PrintWriter(clientSocket.getOutputStream(), true);
			  in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			  }catch (UnknownHostException e) {
			   System.err.println("Don't know about host:" + host);
			   System.exit(1);
			  } catch (IOException e) {
			   System.err.println("Couldn't get I/O for the connection to:" + host);
			   System.exit(1);
			  }
			
			myPanel panel = new myPanel();
			JFrame frame = new JFrame("My Store");
			frame.getContentPane().add(panel);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.pack();
			Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			int height = screenSize.height;
			int width = screenSize.width;
			frame.setSize(width/3, height/2);
			frame.setLocationRelativeTo(null);
			frame.setVisible(true);
	
	}//main
}//client1





package mall;

import java.util.*;


public class ServerProcessor {
	static LinkedList <Item> sitems=null;
	static LinkedList <Item> myitems=null;
	String s=null,uu=null;
	static Store store;
	static ShoppingCart sh=null;
	static Customer c=null;
	
	public ServerProcessor (){
		
		sitems = new LinkedList<Item>();
		myitems = new LinkedList<Item>();
  // create stores in the mall we here use factory pattern to creat it
  
  Store store=new Store("Jeddah Mall ");
  
  
  Item game1=new Item(1,"fulla",90.0);
  store.addItem(game1);
  Item game2=new Item(2,"D chessboard",250.0);
  store.addItem(game2);
  Item game3=new Item(3,"havana",300.0);
  store.addItem(game3);
  Item shoe1=new Item(4,"D puma",400);
 store.addItem(shoe1);
  Item shoe2=new Item(5,"D adidas",300);
  store.addItem(shoe2);
  Item shoe3=new Item(6,"Nike",90);
  store.addItem(shoe3);
  Item book1=new Item(1,"D ITfundemital",300.50);
  store.addItem(book1);
  Item book2=new Item(2," CSfundemital",200.0);
  store.addItem(book2);
  Item book3=new Item(3,"ISfundemital",250.0);
  store.addItem(book3);
  
	}//constructor


public boolean isCustomer(String command)
	{
		if(command.startsWith("customer"))
			return true;
		
		return false;
	}
	
 
 public boolean isShoppingCart(String command)
	{
		if(command.startsWith("shoppingCart"))
			return true;
		
		return false;
	}
	
	public boolean isview(String command)
	{
		if(command.startsWith("view"))
			return true;
		
		return false;
	}
	
		public boolean isadd(String command)
	{
		if(command.startsWith("add"))
			return true;
		
		return false;
	}
	
		public boolean istotal(String command)
	{
		if(command.startsWith("total"))
			return true;
		
		return false;
	}
		public boolean isitems(String command)
		{
			if(command.startsWith("myitems"))
				return true;
			
			return false;
		}	
  
        public boolean isDONE(String command)
	{
		if(command.startsWith("done"))
		return true;
		
		return false;
	}
	//.........................................................
        public void createcustomer(String name){
        	StringTokenizer tokenizer = new StringTokenizer(name,"_");
        	name=tokenizer.nextToken();
        c=new Customer(name);
        store.enter(c);
          	
        }
        //..................
	public void getCart(){
		// create shopping cart
       sh= store.getShopping();
     // add the shopping cart to the customer
      c.addShoppingCart(sh);
	}//shoppingCart
//..........................
    public String view(){
    	sitems =store.items();
    	for(int i=0;i< sitems.size();i++){
    	s=s+"Item number: "+sitems.indexOf(sitems.get(i))+"        Item name: "+sitems.get(i).itname+" \n\n\n";        
    	                                  }
    return s;
}
//...........................
  public void buyitem(String s){
	  StringTokenizer tokenizer = new StringTokenizer(s,"_");
  	   s=tokenizer.nextToken();
  	   int itID=Integer.parseInt(s);
	  sitems =store.items();
      Item item= sitems.get(itID);
      sh.addItem(item);
  }
//...................................    
public double total(){
	 double t=0.0;
	 t=sh.totalprice();
	 return t;
  }
//.....................................
public String viewMyitems(){
	myitems =sh.items();
	for(int i=0;i< myitems.size();i++){
	uu=s+"Item number: "+myitems.indexOf(myitems.get(i))+"        Item name: "+myitems.get(i).itname+" \n\n\n";        
	                                  }
return uu;
}
//...................................    
public String DONE(){
	store.exit(c);
	  return "thanks for visiting us";
  } 
    
}//server processor



package mall;
import java.net.*;
import java.io.*;

public class MallServer {
	public static ServerSocket serverSocket = null;
	public static Socket clientSocket = null;
	public static ServerProcessor processor;
	public static void main(String[] args){
		
		processor =new ServerProcessor();
		
		int port = 1237;


		try {
			serverSocket = new ServerSocket(port);
			
			while(true){
			clientSocket = serverSocket.accept();
			storeThread cipTh = new storeThread(clientSocket);
		    cipTh.start();
			}
			
			
			//serverSocket.close();
			
			}catch(IOException e){
				System.err.println(e.getMessage());
			}

	} // main 
}//MallServer


class storeThread extends Thread{
	Socket client;
	PrintWriter out = null;
	BufferedReader in = null;
	static String inputLine = null;
	public storeThread(Socket client){
		this.client = client;
	}//end myThread Constructor
	
	public void run(){
	
		
		
		

		try {
			
			 out = new PrintWriter(client.getOutputStream(), true);
		      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
		      
             while(true){
			while ((inputLine = in.readLine()) != null) {
	
				if (MallServer.processor.isCustomer(inputLine)) {
					MallServer.processor.createcustomer(inputLine);
					out.println(" you are in the store");
				
				}else if (MallServer.processor.isShoppingCart(inputLine)) {
					MallServer.processor.getCart();
					out.println(" the cart has been added");
				
				}
				else if (MallServer.processor.isview(inputLine)) {
				
					out.println(MallServer.processor.view());

				}else if (MallServer.processor.isadd(inputLine)) {
					MallServer.processor.buyitem(inputLine);
					out.println("item has been added");

				}else if (MallServer.processor.istotal(inputLine)) {
					String t= Double.toString((MallServer.processor.total()));
					out.println(t);
                   }
				
				   else if (MallServer.processor.isitems(inputLine)) {
   					
   					out.println(MallServer.processor.viewMyitems());
                      }
				
				     else if (MallServer.processor.isDONE(inputLine)) {
				       
					    out.println(MallServer.processor.DONE());
					break;
				
				    	 }

				out.flush();

			}//while
             }//while true
		 	
		} catch (IOException e) { // for big try
			e.printStackTrace();
		}finally{
			try{
			out.close();
			in.close();
			MallServer.clientSocket.close();
			MallServer.serverSocket.close();
			}catch (IOException e) { // for big try
				e.printStackTrace();}
		}
		
	}//end run
}//end myThread class



 package mall;

import java.io.IOException;

import javax.swing.JOptionPane;

class myPanel extends javax.swing.JPanel {

	private static final long serialVersionUID = 1L;
	/** Creates new form myPanel */
    public myPanel() {
        initComponents();
    }
      public String output=null, input=null;
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        

        setBackground(new java.awt.Color(102, 0, 102));
        setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Welcome to our Store");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jTextField1.setFont(new java.awt.Font("Times New Roman", 1, 10)); // NOI18N
       // jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextField1.setToolTipText("");
       // jTextField1.addActionListener(new java.awt.event.ActionListener() {
           // public void actionPerformed(java.awt.event.ActionEvent evt) {
            //    jTextField1ActionPerformed(evt);
          //  }
       // });

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Enter your name:  ");

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setText("OK");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(99, 99, 99)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(407, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(208, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(100, 100, 100))
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(146, 146, 146))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(245, Short.MAX_VALUE)
               
                .addGap(195, 195, 195))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                
                .addGap(26, 26, 26))
        );
    }// </editor-fold>                        

//private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
// TODO add your handling code here:
//}                                           

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO add your handling code here:
}                                        

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
    try{ 
	output=jTextField1.getText();          
      Client1.out.println("customer_"+output);
      Client1.out.flush();
      input=Client1.in.readLine();
      JOptionPane.showMessageDialog(null, null, input,0);
     
      myPanel2 page=new myPanel2();
      page.setVisible(true);
    }catch(IOException e){}
    
    } //  jButton1MouseClicked                                  

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextArea jTextField1;
    // End of variables declaration                   
}



  
public class Store{
	// Lest of used variables
    Item item1=null;
String stname=null;// store name
LinkedList <Item> items = new LinkedList<Item>(); // list of the available items
LinkedList <Customer> customers = new LinkedList<Customer>();  // list of the available customers


//Constructor here we make the parameters of the constructor stored in local variables to use it in other methods
  public Store(String name) {
  	this.stname=name;
         }//Constructor
  
  //........................................
   //this method enter customer c to the store
  public void enter(Customer c){
    customers.add(c);	
  }// enter
  //................................
  
  //method to  returns an empty shopping cart
  public ShoppingCart getShopping(){
   return new ShoppingCart();
  }
  
  //........................................
     //this method exits customer c from the store
   public void exit(Customer c){
    customers.remove(c);
   }//exit
  
  //........................................
   // this method returns customers in the store
  public LinkedList<Customer> customers(){
  	return 	customers;
  }//customer
  
  //........................................
  // this method  used when add items and notify its observers when any item  added
public void addItem(Item item){
      items.add(item);
  }// addItem
  //........................................
  // this method returns items available for sale in the store
  public LinkedList<Item> items(){
  	return items;
  }// available items
  
}



public class Customer{
     private ShoppingCart shopingcart=null;
     private String custname=null;
    
    //........................................
    //constructor which declare customer name name;
        public Customer(String name) {
        this.custname=name;
           } // constructor
           
          //add Shopping cart that being used by the customer
         public void addShoppingCart(ShoppingCart sc){
         	this.shopingcart=sc;
         }//add Shopping cart  
  
}



public class ShoppingCart {
	
	LinkedList <Item> items = new LinkedList<Item>(); // to save the items of the shopping cart
     
   public ShoppingCart() {
    	
        } // Constructor
    
    //........................................
     //add item in the shopping cart
    public void addItem(Item item){
         items.add(item);
         
         }//add item
    
//........................................
     //remove item from the the shopping cart
    public void removeItem(Item item){
         items.remove(item);
         
        }//remove item
        
    
   //........................................
    //return items currently in the cart
    public LinkedList<Item> items(){
        return items;
        }//items
   
    //........................................
      //to compute total price of  items with discount or not then return it
    public double totalprice(){
    
    double disprice = 0.0; // discount price
    double nodprice = 0.0; // without discount price
    double totalprice = 0.0; // the total price
    Item it = null;
    String begin = null; //here to save the item name to do comparing
    costStrategy c=null; // define strategy object to initialize it when needed
   
    for(int i=0 ; i<items.size() ; i++){ // loop all the items list
    it=items.get(i); // get the item at index i
    begin = it.itname; // get item name
    if(begin.startsWith("D")){ // if the name begin with d call discountStrategy and it will return discounted price
        c=new discountstrategy();
        disprice =disprice+(c.execute(it));	// here it will sum all discounted items price
    }else  // if the name does not begin with d call withoutdiscountStrategy and it will return normal price	
    {
    	
      	c=new withoutdiscountstrategy();
       nodprice= nodprice+(c.execute(it)); // here it will sum all not discounted items price
     }
    }
    
    totalprice = disprice + nodprice; // sum the all discounted and not discounted price
    return totalprice;	
    }//total price
    
    
}// shoppingCart


I am using eclipse to write my program
and net beans to the interfaces
Thanks For Help

Is This A Good Question/Topic? 0
  • +

Replies To: connection between my client and server seems as it is not working

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2675
  • View blog
  • Posts: 11,300
  • Joined: 20-September 08

Re: connection between my client and server seems as it is not working

Posted 01 January 2012 - 02:24 PM

http://technojeeves....free/118-errors
Was This Post Helpful? 0
  • +
  • -

#3 Hooor  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 86
  • Joined: 26-May 11

Re: connection between my client and server seems as it is not working

Posted 01 January 2012 - 03:21 PM

I attach a picture of the running and the error appears

message dialog suppose to show me message returned from the server but it did not get anything
i do not know why and what is the problem here
THANKS

Attached image(s)

  • Attached Image
  • Attached Image

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1