Data not synchornizing java sockets

Posted by Droid_Interceptor on Stack Overflow See other posts from Stack Overflow or by Droid_Interceptor
Published on 2011-11-19T16:25:29Z Indexed on 2011/11/20 1:51 UTC
Read the original article Hit count: 251

Filed under:
|
|

I am writing a auction server and client and using a class called BidHandler to deal with the bids another class AuctionItem to deal with the items for auction. The main problem I am having is little synchroization problem.

Screen output of client server

as can see from the image at 1st it takes the new bid and changes the value of the time to it, but when one the user enters 1.0 the item seems to be changed to that. But later on when the bid changes again to 15.0 it seems to stay at that price. Is there any reason for that. I have included my code below. Sorry if didnt explain this well.

This is the auction client

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

public class AuctionClient
{

private AuctionGui gui;

private Socket socket;
private DataInputStream dataIn;
private DataOutputStream dataOut;

//Auction Client constructor  String name used as identifier for each client to allow server to pick the winning bidder
public AuctionClient(String name,String server, int port)
{

    gui = new AuctionGui("Bidomatic 5000");
    gui.input.addKeyListener (new EnterListener(this,gui));
    gui.addWindowListener(new ExitListener(this));

    try
    {
        socket = new Socket(server, port);
        dataIn = new DataInputStream(socket.getInputStream());
        dataOut = new DataOutputStream(socket.getOutputStream());
        dataOut.writeUTF(name);
          while (true) 
          {
        gui.output.append("\n"+dataIn.readUTF());
        }
  } 
  catch (Exception e)   
  {
     e.printStackTrace();
  }

}




public void sentBid(String bid)
{
    try
    {
        dataOut.writeUTF(bid);
    }

    catch(IOException e)
    {
        e.printStackTrace();
    }

}

public void disconnect()
{
    try
    {
        socket.close();
    }

    catch(IOException e)
    {
        e.printStackTrace();
    }
}

public static void main (String args[]) throws IOException
{
    if(args.length!=3)
    {
        throw new RuntimeException ("Syntax: java AuctionClient <name> <serverhost> <port>");
    }

    int port = Integer.parseInt(args[2]);
    AuctionClient a = new AuctionClient(args[0],args[1],port);

}
}

The Auction Server

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

public class AuctionServer
{


public AuctionServer(int port) throws IOException
{
    ServerSocket server = new ServerSocket(port);

    while(true)
    {
        Socket client = server.accept();
        DataInputStream in = new DataInputStream(client.getInputStream());
        String name = in.readUTF();
        System.out.println("New client "+name+" from " +client.getInetAddress());

        BidHandler b = new BidHandler (name, client);
        b.start();
    }

}


public static void main(String args[]) throws IOException
{
    if(args.length != 1)
        throw new RuntimeException("Syntax: java AuctionServer <port>");

    new AuctionServer(Integer.parseInt(args[0]));

}


}

The BidHandler

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

public class BidHandler extends Thread
{
Socket socket;
DataInputStream in;
DataOutputStream out;
String name;
float currentBid = 0.0f;
AuctionItem paper = new AuctionItem(" News Paper ", " Free newspaper from 1990 ", 1.0f, false);
protected static Vector handlers = new Vector();

public BidHandler(String name, Socket socket) throws IOException
{
    this.name = name;
    this.socket = socket;

    in = new DataInputStream (new BufferedInputStream (socket.getInputStream()));
    out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
}

public synchronized void run()
{
    try
    {
        broadcast("New bidder has entered the room");
        handlers.addElement(this);


        while(true)
        {
            broadcast(paper.getName() + paper.getDescription()+" for sale at: " +paper.getPrice());

            while(paper.getStatus() == false)
            {


                String message = in.readUTF();
                currentBid = Float.parseFloat(message);
                broadcast("Bidder entered " +currentBid);

                if(currentBid > paper.getPrice())
                {
                    paper.setPrice(currentBid);
                    broadcast("New Higgest Bid is "+paper.getPrice());
                }

                else if(currentBid < paper.getPrice())
                {
                    broadcast("Higgest Bid is "+paper.getPrice());

                }

                else if(currentBid == paper.getPrice())
                {
                    broadcast("Higgest Bid is "+paper.getPrice());

                }

            }
        }

    }

    catch(IOException ex)
    {
        System.out.println("-- Connection to user lost.");
    }

    finally
    {
        handlers.removeElement(this);
        broadcast(name+" left");

        try
        {
            socket.close();
        }
        catch(IOException ex)
        {
            System.out.println("-- Socket to user already closed ?");

        }

    }

}

protected static void broadcast (String message)
{
    synchronized(handlers)
    {
        Enumeration e = handlers.elements();

        while(e.hasMoreElements())
        {
            BidHandler handler = (BidHandler) e.nextElement();

            try
            {

                handler.out.writeUTF(message);
                handler.out.flush();
            }

            catch(IOException ex)
            {
                handler = null;
            }
        }
    }

}



}

The AuctionItem Class

class AuctionItem
{
String itemName;
String itemDescription;
float itemPrice;
boolean itemStatus;

//Create a new auction item with name, description, price and status
public AuctionItem(String name, String description, float price, boolean status)
{
    itemName = name;
    itemDescription = description;
    itemPrice = price;
    itemStatus = status;
}

//return the price of the item.
public synchronized float getPrice()
{
    return itemPrice;   
}

//Set the price of the item.
public synchronized void setPrice(float newPrice)
{
    itemPrice = newPrice;
}

//Get the status of the item
public synchronized boolean getStatus()
{
    return itemStatus;

}

//Set the status of the item
public synchronized void setStatus(boolean newStatus)
{

    itemStatus = newStatus;

}

//Get the name of the item
public String getName()
{

    return itemName;

}

//Get the description of the item
public String getDescription()
{

    return itemDescription;

}


}

There is also simple GUI to go with this that seems to be working fine. If anyone wants it will include the GUI code.

© Stack Overflow or respective owner

Related posts about java

Related posts about sockets