0

I am currently learning socket programming in java. I have tried to create some basic application which worked pretty well. Now, I am trying to do a client/Server application with jdbc. However, I am facing some issues in the clientside. I have a Jpanel which has a Jbutton add product and delete product and also in this panel I have a Jtable that shows all the products present in the database. I am using Object streams to allow data to be transferred. The problem is that when an operation(add,delete,show) has already been done I can't use the ObjectOutputStream again to undergo another operation. The Jpanel panel freezes without giving any error. I have flushed all the output Streams an yet the problem is still here. But when an operation runs for the first time it runs successfully, i assume that all code for the operations are running well. I would really appreciate some help please. Sorry for not putting the naming rules. Thank you.

Server

public class Serverframe extends javax.swing.JFrame 
    /**
     * Creates new form Serverframe
     */
    ObjectOutputStream toClientO;
    ObjectInputStream fromClientO;
    Socket clientconnection=null;
    Socket request;
    Socket reqOperation;


    Connection con =null;
    public Serverframe() throws IOException {
        initComponents();
       con=DBconnnection.conn();
      
       
        
    }

    private void btnstartActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            btnstart.setEnabled(false);
            btnstart.setVisible(false);
            btnstop.setVisible(true);
            btnstop.setEnabled(true);
            Serverside();
        } catch (IOException ex) {
            Logger.getLogger(Serverframe.class.getName()).log(Level.SEVERE, null, ex);
        }
               
    }                                        

    private void btnstopActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        btnstart.setVisible(true);
        btnstart.setEnabled(true);
        btnstop.setVisible(false);
        btnstop.setEnabled(false);
        
        
        
    }                                       
     
    public void Serverside() throws IOException{         
        try{
            int serverport = 1234;
            ServerSocket serversocket = new ServerSocket(serverport);
           // System.out.println("server is now ready....");
            txtshowtext.append("server is now ready....");
            
           while(true){
             Socket clientconnection=serversocket.accept(); /*waiting for clients to connect*/
              Thread t=new Thread(new clienthandler(clientconnection));
                  t.start();
               
                 
                
        }
       }
                    catch(IOException ioe)
       {
          System.out.println("error");
              txtshowtext.append("error");
       }
    }/*end of constructor*/
 
 
    class clienthandler implements Runnable
    {
    public clienthandler( Socket clientconnection)
    {
            

        try{
                   request = clientconnection;
           fromClientO=new ObjectInputStream (request.getInputStream( ));
           toClientO=new ObjectOutputStream( request.getOutputStream());
        }catch(IOException io)
          {
            System.out.println("can't take i/o stream");
                        txtshowtext.append("can't take i/o stream");
            }
                
       }
        @Override 
         public void run( )
      {
           

       String firstname = null; 
       String lastname = null;
       String phone = null;
       String email = null; 
       String address = null; 
       String username = null; 
       String password = null;
       String test1="";
       PreparedStatement pst = null;
       PreparedStatement ps = null;
       ResultSet rst=null;
       ResultSet rs=null;
       String user=null;
       String pass=null;
       String Product = null;
       String Brand = null;
       String Model = null;
       String Price = null;
       String Stock = null;
       String Features = null;
       String Category = null;
       String PhotoPath = null;
       Statement statement=null;
       
       try {
             test1=(String)fromClientO.readObject();          
          } catch (IOException | ClassNotFoundException ex) {
              ex.printStackTrace();
          }
       // **********************************ADD PRODUCT*********************************

              if(test1.equals("addproduct"))
       {    ArrayList<String> product=new ArrayList<>();
      try {
              Object o=new Object();
              o=fromClientO.readObject();
               product=(ArrayList<String>) o;
               Product = product.get(0);
               Brand = product.get(1);
               Model = product.get(2);
               Price = product.get(3);
               Stock = product.get(4);
               Features = product.get(5);
               Category = product.get(6);
               PhotoPath = product.get(7);
          } catch (IOException | ClassNotFoundException ex) {
              ex.printStackTrace();
          }
          
             try {
            
            String sql1="insert into PRODUCT(Product,Brand,Model,Price,Stock,Features,Category_Id,imagepath) values(?,?,?,?,?,?,?,?)";
            pst=con.prepareStatement(sql1);
            pst.setString(1,Product);
            pst.setString(2,Brand);
            pst.setString(3,Model);
            pst.setInt(4,Integer.parseInt(Price));
            pst.setInt(5,Integer.parseInt(Stock));
            pst.setString(6,Features);
            pst.setInt(7,Integer.parseInt(Category));
            pst.setString(8,PhotoPath); 
            
            
            pst.execute();            
            toClientO.writeObject(1);
            toClientO.flush();
         
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
        finally{
            try{
                pst.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
       
         }
              
  
//SHOW PRODUCTS
 if(test1.equals("showproducts"))
       {    
           try{
           ArrayList<Product> productList = new ArrayList<>();

           String query1 = "SELECT * FROM Product";
           statement =con.createStatement();
            rs = statement.executeQuery(query1);
           Product product;
           while(rs.next()){
           product =new Product(rs.getInt("Product_Id"), rs.getString("Product"), rs.getString("Brand"),rs.getString("Model"),rs.getString("Features"), rs.getInt("Stock"),rs.getInt("Price"), rs.getInt("Category_Id"),rs.getString("imagepath"));
         productList.add(product);
           }
        toClientO.writeObject(productList);
        toClientO.flush();
     
           }catch(Exception ex){
               ex.printStackTrace();
           }
           finally{
               try {
                   statement.close();
                  // toClientO.flush();
                   rs.close();
      
               } catch (SQLException ex) {
                   ex.printStackTrace();
               }
           }
               }
 

//DELETE PRODUCTS
 
 if(test1.equals("delproducts")){
 
 try{
           
            int value = Integer.parseInt((String)fromClientO.readObject());            
            String query= "DELETE FROM Product WHERE Product_Id =?";
            pst = con.prepareStatement(query);
            pst.setInt(1,value);
            pst.execute();            
            toClientO.writeObject(1);
              toClientO.flush();
           }
 
 catch(Exception ex){
    ex.printStackTrace();
 }
 finally{
                try {
                  
                    pst.close();
                    rs.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
 }
       }
           
       }            
          
    } 


               


**ClIENT**

 public void adminside(){
    try{
               socket=new Socket("localhost", 1234); /*making connection*/
               toServerO= new ObjectOutputStream( socket.getOutputStream());
               fromServerO= new ObjectInputStream (socket.getInputStream( ));
 
                       System.out.println("Connection Successful");
        }catch(IOException ioe)
            {
                            ioe.printStackTrace();
             System.out.println("can't connect");
        }   
    }

****************************ADD PRODUCTS*******************
private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {            
  if(txtproduct.getText().isEmpty() || txtbrand.getText().isEmpty() || txtmodel.getText().isEmpty() || txtprice.getText().isEmpty() || txtquantity.getText().isEmpty() || txtfeatures.getText().isEmpty() || combocategory.getSelectedIndex() == 0){
        JOptionPane.showMessageDialog(rootPane, "Required Fields are not Filled", "Fields are Empty",1);}
        else{
        try {
        toServerO.writeObject("addproduct");
        ArrayList<String> product=new ArrayList<>();
        product.add(txtproduct.getText().trim());
        product.add(txtbrand.getText().trim());
        product.add(txtmodel.getText().trim());
        product.add(txtprice.getText().trim());
        product.add(txtquantity.getText().trim());
        product.add(txtfeatures.getText().trim());
        product.add(String.valueOf(combocategory.getSelectedIndex()));
        product.add(txtphotopath.getText().trim());
        
        
        toServerO.writeObject(product);
        toServerO.flush();
        int st=0;
        try {
        st=(int)fromServerO.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            // Logger.getLogger(Login_JFrame.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
        }
        if(st==1){
        JOptionPane.showMessageDialog(rootPane, "Product Successfully Added", "Success",1);
        
        resetAdd();
        }
        else{
        JOptionPane.showMessageDialog(rootPane, "An Error Has Occured, Please Try Again...", "Error",1);
        }
        } catch (IOException ex) {
        // Logger.getLogger(SignUp_JFrame.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
        }

//********************Delete Product****************************

 private void delEntryActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        try{
     toServerO.writeObject("delproducts");
     toServerO.flush();
        if(txtprodId.getText().isEmpty()){
             JOptionPane.showMessageDialog(rootPane, "Select a Record First", "Field is Empty",1);
        }
        else{
     
try{
        int dialogButton = JOptionPane.YES_NO_OPTION;
         int dialogResult = JOptionPane.showConfirmDialog(this, "Do You Really Want to Delete this Record?", "Delete Product", dialogButton);
         if(dialogResult == 0) {
  try{           
            String value = txtprodId.getText().trim();
          
           
           toServerO.writeObject(value);
           toServerO.flush();
          
          
           int st=0;
           
           try {
            st=(int)fromServerO.readObject();
        } catch (IOException | ClassNotFoundException ex) {
          ex.printStackTrace();
        }
           
           if(st==1){
            DefaultTableModel model = (DefaultTableModel)tblproducts.getModel();
            model.setRowCount(0);
           // show_products();
            reset();
             JOptionPane.showMessageDialog(rootPane, "Record successfully deleted", "Deleted",1);
             
           }
           else{
               JOptionPane.showMessageDialog(rootPane, "An Error took Place", "Error",1);
           } 
            
        }catch(HeadlessException ex){
          ex.printStackTrace();
        } 
         }
 
      
         }
            catch(Exception ex){
            ex.printStackTrace();
            }
        }
        }catch(IOException ex){
           ex.printStackTrace();
        }
    }  


//******************** Show Products*************
public ArrayList<Product> pList(){
        
       ArrayList<Product> productList=new ArrayList<>();
             try {
               Object o=new Object();
               o=fromServerO.readObject();
            productList=(ArrayList<Product>) o;
          } catch (Exception ex) {
              ex.printStackTrace();
          }
             
return productList;
    }
   
   
    public void show_products() throws IOException{
        
         try{
     toServerO.writeObject("showproducts");    
     toServerO.flush();
        }catch(IOException ex){
            ex.printStackTrace();     
        }
        
        
        ArrayList<Product> list = pList();
        DefaultTableModel model = (DefaultTableModel)tblproducts.getModel();
        Object[] row = new Object[9];
        model.setRowCount(0);
        for(int i=0;i<list.size();i++){
            row[0]=list.get(i).getproductId();
            row[1]=list.get(i).getproduct();
            row[2]=list.get(i).getbrand();
            row[3]=list.get(i).getmodel(); 
            row[4]=list.get(i).getfeatures();
            row[5]=list.get(i).getstock();
            row[6]=list.get(i).getprice();
            row[8]=list.get(i).getcatId();
            row[7]=list.get(i).getimagepath();
            model.addRow(row);
        }
    }
    


        }
        
    }     

                                           
               
        
          
   
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Sockets need to execute in a separate Thread since they block waiting for input which is why your GUI freezes. – camickr Jun 26 '21 at 17:18
  • @camickr hi , thanks for replying, but i didn't understand what you mean. – Neelkanth Mawood Jun 26 '21 at 17:49
  • With a GUI all code executes on the `Event Dispatch Thread (EDT)`. So listener code and repainting is done on the EDT. With a client/server app the client and server block waiting for requests. This is done by using a `while (true)` loop. Therefore this code needs to execute in a separate Thread so you don't block the EDT. When the GUI "freezes" this indicates that some blocking code or long running task is executing on the EDT. From the code posted is looks like the server execute on a separate Thread. The client looping code also needs to execute execute on a separate Thread. – camickr Jun 26 '21 at 21:36
  • Check out: https://stackoverflow.com/questions/7301205/how-would-i-go-about-making-my-paint-for-my-jframe-automatically-update/7301731#7301731. You can download my one and only attempt at writing a client/server app. It attempts to keep the text in a text pane in sync with all clients connected to the server. So not exactly the same as you are doing but maybe it will help? I would think your server logic would be simpler since you just receive a request and reply by to the client. – camickr Jun 26 '21 at 21:42
  • Oh okay, i think, I understand it now. Thank You very much @camickr – Neelkanth Mawood Jun 27 '21 at 06:49

0 Answers0