Link to home
Start Free TrialLog in
Avatar of danBosh
danBoshFlag for United Kingdom of Great Britain and Northern Ireland

asked on

client - server problem

I am developing an online auction using java rmi, and want to simulate the auctioneers instrustions on the client side, so that when a user places a bid, a text label within an applet representing the auctionners instruction will then ask for the next amount, etc.

What I am having problems with is how to relay the "going once", "going twice" and "gone" instrustions in that these will have to appear a set period of time after the final bid has been placed, so i will need a while loop or something on the server which  contantly checks to see if the required amount of time has passed. My question is how do i do with while also allowing the server to recieve bids, and prefrom other operations?
Avatar of glottis
glottis
Flag of Pakistan image

multi threading.
on thread will be listing for peoples bid and the other thread will keep a timer on when two say going once, twice sold.
Avatar of Mayank S
Use threading at the server-side.

In your main () function, use a ServerSocket object:

class MainServer
{
  public static void main ( String args[] )
    throws Exception
  {
    ServerSocket ss = new ServerSocket ( <port-no> ) ;
    Socket s = ss.accept () ; // accept a new connection from a client
    new ServerThread ( s ) ; // start a new thread to serve this client dedicatedly

  } // end of main ()

} // class definition over

class ServerThread extends Thread
{
  Socket s ;
  BufferedReader br ;
  PrintWriter pw ;

  ServerThread ( Socket s )
  {
    try
    {
      this.s = s ;  
      br = new BufferedReader ( new InputStreamReader ( s.getInputStream () ) ) ;
      pw = new PrintWriter ( s.getOutputStream (), true ) ;

    } // end of try block

    catch ( Exception e )
    {
      System.out.println ( "\n Exception: " + e ) ;
      return ;

    } // end of catch block

    start () ; // new thread

  } // end of constructor ()

  public void run ()
  {
    try
    {
      while ( true )
      {
        // put entire functionality of the server here
        // use pw.println () to send data,
        // br.readLine () to read

        if ( <some-exiting-condition> ) // like, the client wishes to log out
          return ; // kill this thread

      } // end while
     
    } // end of try block

    catch ( Exception e ) // client gets disconnected by, say, a power-failure
    {
      System.out.println ( "\n Exception: " + e ) ;
      return ; // kill this thread

    } // end of catch block

  } // end of run ()

} // class definition over


Hope that helps as a building block!

Mayank.

     
Avatar of danBosh

ASKER

i counldnt really do it like that because where you say "put entire functionality of the server here" would not be possible because my server has many methods used for the auction and rmi communication?
Maybe you can define those methods inside the ServerThread class and call them from the run () method??

Mayank.
Avatar of danBosh

ASKER

my server class looks like this, i just need a method like which will be checked approx every 0.1secs:
 
if((lastBid-currenttime)>30)updateLabel("going once")
if((lastBid-currenttime)>40)updateLabel("going twice")
if((lastBid-currenttime)>50)updateLabel("gone")




import java.rmi.*;
import java.rmi.server.*;
import java.net.*;
import java.util.*;

public class Auctioneer extends UnicastRemoteObject implements AuctionInterface
{
    //private String minBid;
    private String currentBid;
    private String product;
    private String highestBidder;

    // To hold the registered clients
    private Vector clientList = null;
    double delays [];
    int price=0;

    public Auctioneer(String product)throws RemoteException//minBid removed
    {
       super();
       setProduct(product);
       clientList = new Vector();
       currentBid="0";
       highestBidder="fhfd";
    }

    public String getCurrentBid() throws RemoteException
    {
        return currentBid;
    }
   
    public String bosh()
    {
          return "bosh";
      }

    /*public String getMinBid() throws RemoteException
    {
        return minBid;
    }
    */
   
    public String getHighestBidder()throws RemoteException
    {
          //System.out.println("New Highest Bidder"+highestBidder);
          return highestBidder;
      }

    public String getProduct() throws RemoteException
    {
        return product;
    }
   
    public String getInstruction() throws RemoteException
    {
        return "Do I hear #"+nextPrice();
    }
   
    public int nextPrice()
    {
          if(price<100)
            {
                  return price+5;
            }
            else if(price<500)
            {
                  return price+25;
            }
            else
            {
                  return price+=50;
            }
      }
   
    public void incrementPrice(String clientName)throws RemoteException
    {
   
   
          Updateable thingToUpdate = null;
          if(clientName !=getHighestBidder())
          {
                price = Integer.parseInt(currentBid);//.trim() possible?
          
              if(price<100)
                  {
                        price+=5;
                  }
                  else if(price<500)
                  {
                        price+=25;
                  }
                  else
                  {
                        price+=50;
                  }
                  currentBid = Integer.toString(price);
                  highestBidder=clientName;
            
                  System.out.println("currentBid: "+currentBid);
                  System.out.println("Highest Bidder: "+highestBidder);
                  
                  for(Enumeration clients = clientList.elements();clients.hasMoreElements();)
              {
                    System.out.println("NOTIFYING");
                thingToUpdate = (Updateable) clients.nextElement();
                //thingToNotify.notify(new Integer(0));
                 thingToUpdate.update(new Integer(0));
              }
          }
          else
          {
                
        }         
      }
      
      
      public void delay() throws RemoteException
      {
            Updateable thingToUpdate = null;
            delays = new double[clientList.size()];
            double start=0;
            double total=0;
            int c=0;
            
            for(Enumeration clients = clientList.elements();clients.hasMoreElements();)
        {
              thingToUpdate = (Updateable) clients.nextElement();
              
              
              for(int i=0;i<3;i++)
              {
                    start = System.currentTimeMillis();
                    thingToUpdate.dummy();
                    total+= (System.currentTimeMillis()-start);
              }
              delays[c]=(total/3.0);
              total=0.0;
              c++;
        }
            
            
      }      

      
    public void setProduct (String p)
    {
        product = p;
    }

    public void registerForUpdate(Updateable n) throws RemoteException
    {
        clientList.addElement(n);
        delay();
        for(int i=0;i<delays.length;i++)
        {
              System.out.println("Client Delay in Milli Seconds "+delays[i]);
          }
    }

    public static void main(String [] args)
    {
          System.out.println("SERVER STARTED");
        if(args.length == 0)
        {
            System.out.println("USAGE: java <product name>");
            System.exit(0);
        }
   
       
        System.setSecurityManager(new RMISecurityManager());
       
        try
        {
            Auctioneer thisOne = new Auctioneer(args[0]);//args 1 removed
            Naming.rebind(args[0], thisOne);
           
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}


Something like this:

class TimeChecker extends Thread
{
  Date initialTime ;
  Date currentTime ;
  int timeOutLimit = 60000 ; // 60 seconds or 60 milliseconds

  TimeChecker () // oonstructor ()
  {
    initialTime = new Date () ;
    start () ;

  } // end of constructor ()

  public void run ()
  {
    currentTime = new Date () ;
   
    if ( currentTime.getTime () - initialTime.getTime () > timeOutLimit )
    // over 60 seconds

  } // end of run ()

} // class definition over

// put a TimeChecker object in the Auctioneer class - it will spawn a new thread and automatically keep checking the time

public class Auctioneer extends UnicastRemoteObject implements AuctionInterface
{
  public Auctioneer ( String product )
    throws RemoteException
  {
    super () ;
    new TimeChecker () ;
....
....

  } // end of constructor ()

} // class definition over

   
Hope that helps!

Mayank.
Declare timeOutLimit as 'long' above.

Mayank.
Avatar of danBosh

ASKER

mayankeagle

i tried this and it just runs the tread once an then carries on as normal?
ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial